题目:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
我的代码:
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int ele;
while(!stack1.empty()){
ele=stack1.top();
stack1.pop();
stack2.push(ele);
}
int ans=stack2.top();
stack2.pop();
while(!stack2.empty()){
ele=stack2.top();
stack2.pop();
stack1.push(ele);
}
return ans;
}
private:
stack<int> stack1;
stack<int> stack2;
};
优秀代码:
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
int t=stack2.top();
stack2.pop();
return t;
}
private:
stack<int> stack1;
stack<int> stack2;
};
两段代码的区别在pop()的实现上。
我的代码的pop过程如下:
1,将栈1的元素全部压入栈2;
2,弹出栈2顶部元素;
3,然后将栈2的元素再全部压入栈1
之所以有第三步是为了维护栈1中的先后顺序,但实际上不需要!因为队列的特点是FIFO,而栈1新添的元素本身就比栈2后,自然会在栈2全部出队后才出队,不需要维护先后顺序。等栈2取完,再将栈1压入栈2,供下次出队。
另外,需要注意STL中的stack.pop()返回的是void,即pop()函数只删不取,对应的top()函数则只取不删。两者结合来实现栈的弹出。