1、入队时,将元素压入s1;
2、出队时,判断s2是否为空,如不为空,则直接弹出顶元素;如为空,则将s1的元素逐个“倒入”s2,把最后一个元素弹出并出队。
避免了反复“倒”栈,仅在需要时才“倒”一次。
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 result; if(!stack2.isEmpty()){ result=stack2.pop(); }else{ while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } result=stack2.pop(); } return result; } }
用两个队列(Queue)实现栈(Stack)
1、入栈:将元素进队列s1;
2、出栈:判断队列s1中元素的个数是否为1,如果等于1,则出队列,否则将队列s1中的元素 以此出队列并放入队列s2,直到队列s1中的元素留下一个,然后队列s1出队列,再把队列s2中的元素出队列以此放入队列s1中。