class MyQueue {
private:
stack<int> sta;
stack<int> sta1;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
while (!sta.empty()) {
sta1.push(sta.top());
sta.pop();
}
sta.push(x);
while (!sta1.empty()) {
sta.push(sta1.top());
sta1.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int temp = sta.top();
sta.pop();
return temp;
}
/** Get the front element. */
int peek() {
return sta.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return sta.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/
下面这个push是错的
void push(int x) {
if(sta.empty())
sta.push(x);
else{
for(int i = 0; i < sta.size(); ++i){
sta1.push(sta.top());
sta.pop();
}
sta.push(x);
for(int i = 0; i < sta1.size(); ++i){
sta.push(sta1.top());
sta1.pop();
}
}
}
因为stack.size()一直在变,不是我们以为的那个size,应该为
void push(int x) {
if(sta.empty())
sta.push(x);
else{
int siz = sta.size();
for(int i = 0; i < siz; ++i){
sta1.push(sta.top());
sta.pop();
}
sta.push(x);
int siz1 = sta1.size();
for(int i = 0; i < siz1; ++i){
sta.push(sta1.top());
sta1.pop();
}
}
}
前面的思路是还没空,就一直往外倒,
第二个是计数操作