19

问答题 19 /22

用两个栈实现一个队列的功能?要求给出算法和思路!
设2个栈为A,B, 一开始均为空.

入队:
将新元素push入栈A;

出队:
(1)判断栈B是否为空;
(2)如果不为空,则将栈A中所有元素依次pop出并push到栈B;
(3)将栈B的栈顶元素pop出;


这样实现的队列入队和出队的平摊复杂度都还是O(1), 比上面的几种方法要好。

参考答案

/*
声明两个栈 stackPush,用来保存入栈的数据,stackPop用来保存出站的数据。
入栈时,只需向stackPush添加数据。当stackPop栈中的数据为空时,
就一次性把stackPush中的数据导入到stackPop中,避免二次添加时,出来的数据不一致性的问题。

*/
import java.util.Stack;

public class TwoStacksImplementQueue {

	public static class TwoStacksQueue {
		public Stack<Integer> stackPush;
		public Stack<Integer> stackPop;

		public TwoStacksQueue() {
			stackPush = new Stack<Integer>();
			stackPop = new Stack<Integer>();
		}

		public void push(int value) {
			stackPush.push(value); }

		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();
		}
	}
}