题解 | #用两个栈实现队列#
用两个栈实现队列
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() { int size = stack1.size(); // statk2有的话直接pop,没有在去statk1中pop if (stack2.isEmpty()) { int i = 0; while (i < size) { stack2.push(stack1.pop()); i++; } } return stack2.pop() ; } }
1.栈就是先进后出,如果两个就可以变成先进先出.
2.第二个栈:没有数据时候把第一个栈的数据全部拿出来;有数据就直接pop()