用栈实现队列
两个栈。一个输出栈,负责pop和peek。一个输入栈,负责push。
输入直接输入。输出,先将输入栈的元素压入输出栈,再输出。
class MyQueue { Deque<Integer> inStack; Deque<Integer> outStack; public MyQueue() { inStack = new LinkedList<Integer>(); outStack = new LinkedList<Integer>(); } public boolean Empty(){ return outStack.isEmpty()&&inStack.isEmpty(); } public void in2out(){ while(!inStack.isEmpty()){ outStack.push(inStack.pop()); } } public void push(int x){ inStack.push(x); } public int pop(){ // if(!outStack.isEmpty()){ 错误的,加!是不空 if(outStack.isEmpty()){ in2out(); } return outStack.pop(); } public int peek(){ if(outStack.isEmpty()){ in2out(); } return outStack.peek(); } }
用队列实现栈
两个队列。队列1负责存队列元素,队列2负责辅助入栈。出栈都是队列1负责。入栈时,先入队2,再把1的元素入队2,然后交换1和2。保证队头是先进的。
Queue操作是,offer,poll
class MyStack { Queue<Integer> q1; Queue<Integer> q2; public MyStack() { q1 = new LinkedList<Integer>(); q2 = new LinkedList<Integer>(); } public void push(int x) { q2.offer(x); while(!q1.isEmpty()){ q2.offer(q1.poll()); } Queue<Integer> temp=q2; q2=q1; q1=temp; } public int pop() { return q1.poll(); } public int top() { return q1.peek(); } public boolean empty() { return q1.isEmpty(); } }