题目: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;
}
/**************************************************************
Problem: 1512
Language: C++
Result: Accepted
Time:620 ms
Memory:1656 kb
****************************************************************/