两个队列一个栈
public static class TwoQueuesStack { private Queue<Integer> queue; private Queue<Integer> help; public TwoQueuesStack() { queue = new LinkedList<Integer>(); help = new LinkedList<Integer>(); } public void push(int pushInt) { queue.add(pushInt); } public int peek() { if (queue.isEmpty()) { throw new RuntimeException("Stack is empty!"); } while (queue.size() != 1) { help.add(queue.poll()); } int res = queue.poll(); help.add(res); swap(); return res; } public int pop() { if (queue.isEmpty()) { throw new RuntimeException("Stack is empty!"); } while (queue.size() > 1) { help.add(queue.poll()); } int res = queue.poll(); swap(); return res; } private void swap() { Queue<Integer> tmp = help; help = queue; queue = tmp; } } }
两个栈一个队列
push栈
pop栈
pop栈中非空,push不可入pop栈
pop栈为空,push倒入pop直到push为空。
public static class TwoStacksQueue { private Stack<Integer> stackPush; private Stack<Integer> stackPop; public TwoStacksQueue() { stackPush = new Stack<Integer>(); stackPop = new Stack<Integer>(); } public void push(int pushInt) { stackPush.push(pushInt); } public int poll() { if (stackPop.empty() && stackPush.empty()) { throw new RuntimeException("Queue is empty!"); } else if (stackPop.empty()) { while (!stackPush.empty()) { stackPop.push(stackPush.pop()); } } return stackPop.pop(); } public int peek() { if (stackPop.empty() && stackPush.empty()) { throw new RuntimeException("Queue is empty!"); } else if (stackPop.empty()) { while (!stackPush.empty()) { stackPop.push(stackPush.pop()); } } return stackPop.peek(); } }