Problem:
As the title described, you should only use two stacks to implement a queue's actions.
The queue should support push(element)
, pop()
and top()
where pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
Notes:
1.注意pop()之前先要保存top()的值再pop.
Code:
class MyQueue {
public:
stack<int> stack1;
stack<int> stack2;
MyQueue() {
// do intialization if necessary
}
void push(int element) {
// write your code here
stack1.push(element);
}
int pop() {
// write your code here
int element;
if (stack2.empty()) {
while (!stack1.empty()) {
element = stack1.top();
stack1.pop();
stack2.push(element);
}
}
element = stack2.top();
stack2.pop();
return element;
}
int top() {
// write your code here
int element;
if (stack2.empty()) {
while (!stack1.empty()) {
element = stack1.top();
stack1.pop();
stack2.push(element);
}
}
return stack2.top();
}
};