通过两个队列实现栈
public class TwoQueueAsStack {
Queue<Integer> data;
Queue<Integer> help;
public TwoQueueAsStack() {
data=new LinkedList<>();
help=new LinkedList<>();
}
public Integer pop() {
if(data.isEmpty())
return null;
while(data.size()>1)
help.add(data.poll());
int res=data.poll();
swap();
return res;
}
public void push(Integer num) {
data.add(num);
}
public Integer peek() {
if(data.isEmpty())
throw new RuntimeException("Stack is empty");
while(data.size()>1)
help.add(data.poll());
int res=data.poll();
help.add(res);
swap();
return res;
}
public void swap() {
Queue<Integer> tmp=data;
data=help;
help=tmp;
}
public static void main(String[] args) {
TwoQueueAsStack stack=new TwoQueueAsStack();
stack.push(2);
stack.push(3);
stack.push(1);
System.out.println(stack.peek());
System.out.println(stack.pop());
System.err.println(stack.peek());
System.err.println(stack.peek());
}
}