题解 | #用两个栈实现队列#
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
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 stack1.push(node); } public int pop() { //把stack1的元素全部装进stack2,最先进入stack1的元素,一开始在stack1底部,现在在stack2的最上面 // 直接对stack2进行pop 就能把最开始进入stack1的元素顶出来 while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } // 外部看来,执行一次pop操作,返回队列的元素 int res = stack2.pop(); // 下面的操作很关键,取出元素之后,之后还要继续push元素,又得把stack2的元素放回stack1 while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } return res; } }
两个栈确实可以实现队列,先进先出。
push操作全在stack1进行,很简单。
pop操作在stack2进行。首先把stack1的元素全部放进stack2,再对stack2进行pop操作就可以把最开始进入stack1的元素弹出来。还有一个步骤很关键,就是要把stack2的元素重新放进stack1。