每个数据只转移一次,当且仅当stk2为空时把stk1中的数据转移到stk2中。
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> stk1,stk2;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stk1.push(x);
}
void copy(stack<int> &a,stack<int> &b){
while(!a.empty()){
b.push(a.top());
a.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(stk2.empty()){
copy(stk1,stk2);
}
int k = stk2.top();
stk2.pop();
return k;
}
/** Get the front element. */
int peek() {
if(stk2.empty()){
copy(stk1,stk2);
}
return stk2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
if(stk2.empty()){
copy(stk1,stk2);
}else return false;
if(stk2.empty()) return true;
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/
6666666666