题解 | #用两个栈实现队列#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
用两个栈来实现一个队列,分别完成在队列尾部插入整数(push)和在队列头部删除整数(pop)的功能。 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
算法实现
由于队列具有先进先出原则,我们考虑入队时让元素进到栈1中,在出队时先将栈1中的元素全部放入栈2当中,这时元素的顺序刚好发生改变,此时再从栈2中弹出元素,这时出栈的元素刚好是最早进队的元素,满足先进先出原则。
注:当从栈2中弹出元素后,应将栈2中剩余元素再全部返回栈1中,这样方便下次出队。
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() { while(!stack1.isEmpty()){ int e1 = stack1.pop(); stack2.push(e1); } int result = stack2.pop(); while(!stack2.isEmpty()){ int e2 = stack2.pop(); stack1.push(e2); } return result; } }