题解 | 用两个栈实现队列
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
import java.util.*; 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.empty()){ int temp =stack1.pop(); stack2.push(temp); } int r = stack2.pop(); while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } return r; } }
分析一下,这个算法题使用两个栈来实现一个类似于队列的形式,对于第一个栈,作为一个中转栈,先将元素入栈,然后将元素出栈,然后再进入第二个栈,将栈顶元素输出,同时将除了栈顶元素的其他元素仍旧放到第一个栈中。