输入: 6 add 1 add 2 add 3 peek poll peek 输出: 1 2
栈的特点是先进后出,队列的特点是先进先出,用俩个栈正好能把顺序发过来实现类似队列的操作。
1)一个栈作为压入栈,在压入时只往这个栈中压入,另一个栈作为弹出栈,在弹出数据的时候只从这个栈弹出。
2)因为数据压入栈的时候顺序是先进后出的,那么只要把压入栈的数据再压入到弹出栈,顺序就变回来了。
import java.util.Stack; import java.util.Scanner; class TwoStacksQueue{ public Stack<Integer> stackPush; public Stack<Integer> stackPop; public TwoStacksQueue(){ stackPush = new Stack<Integer>(); stackPop = new Stack<Integer>(); } public void pushToPop(){ if(stackPop.empty()){ while(!stackPush.empty()){ stackPop.push(stackPush.pop()); } } } public void add(int pushInt){ stackPush.push(pushInt); pushToPop(); } public int poll(){ if(stackPop.empty() && stackPush.empty()){ throw new RuntimeException("Queue is empty!"); } pushToPop(); return stackPop.pop(); } public int peek(){ if(stackPop.empty() && stackPush.empty()){ throw new RuntimeException("Queue is empty!"); } pushToPop(); return stackPop.peek(); } } public class Main{ public static void main(String[] args){ TwoStacksQueue twostacksqueue = new TwoStacksQueue(); Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); for(int i=0;i<n;i++){ String op = scanner.next(); if(op.equals("add")){ int x = scanner.nextInt(); twostacksqueue.add(x); }else if(op.equals("poll")){ twostacksqueue.poll(); }else if(op.equals("peek")){ System.out.println(twostacksqueue.peek()); } } } }