您的位置:首页 > 编程语言 > C语言/C++

用两个栈实现队列 c++ 9度题目号1512

2015-10-25 15:23 357 查看
题目:http://ac.jobdu.com/problem.php?pid=1512

思路为用两个栈,一个入队列一个出队列。

对自定义队列MyQueue执行push的时候直接往入队列栈push。

对自定义队列MyQueue执行pop的时候如果出队栈为空而入队栈不为空,就将入队栈中所有元素pop出来push到出队栈中,然后pop一次出队栈。

#include <iostream>

#include <cstdio>

#include <stack>

#define MAXSIZE 100000

using namespace std;

class MyQueue{

private:

stack<int> in, out;

public:

MyQueue() {}

~MyQueue() {}

void push(int key) {

in.push(key);

}

void pop() {

if (out.empty()) { //如果出队栈为空

if (!in.empty()) { //如果入队栈不为空

while (!in.empty()) { //当入队栈不为空

out.push(in.top()); //将入队栈的所有数据转移到出队栈中

in.pop();

}

}

}

if (!out.empty()) { //如果出队栈不为空

cout << out.top() << endl; //输出 出队栈

out.pop();

}

else cout << "-1" << endl;

}

void clear_() {

while (!in.empty()) in.pop();

while (!out.empty()) out.pop();

}

};

int main()

{

MyQueue Q;

int n;

while (cin >> n) {

while (n--) {

string s;

int key;

cin >> s;

if (s == "PUSH") {

cin >> key;

Q.push(key);

}

else if (s == "POP") Q.pop();

}

Q.clear_();

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: