题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
分析:
栈是先进后出,而队列是先进先出。可以用两个栈实现队列的Push和Pop操作。栈s1用来记录Push的值,而因为Pop要取出最先压入的值,因此若栈s2为空时,将s1中的值从上至下依次压入s2中,此时s2中栈顶元素即为最先压入s1中的值。
C++代码:
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int res = 0;
if(stack2.size() > 0)
{
res = stack2.top();
stack2.pop();
}
else if(stack1.size() > 0)
{
while(stack1.size() > 0)
{
int top1 = stack1.top();
stack2.push(top1);
stack1.pop();
}
res = stack2.top();
stack2.pop();
}
return res;
}
private:
stack<int> stack1;
stack<int> stack2;
};
Java代码:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
int res = 0;
if(stack2.isEmpty())
{
while(!stack1.isEmpty())
{
stack2.push(stack1.pop());
}
}
res = stack2.pop();
return res;
}
}