题解 | #用两个栈实现队列#
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
import java.util.Stack; public class Solution { int count = 0; //栈的特点是先进后出 //队列的特点是先进先出 //进去的时候,直接放进一个栈s1里 //出来的时候,先都取出来放进另一个栈s2里,再取出来,就是先进先出了. //取出来一次之后,需要把s2里所有的元素依次放回s1 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()){ stack2.push(stack1.pop()); } int j = stack2.pop(); if(!stack2.isEmpty()){ stack1.push(stack2.pop()); } return j; } }