题解 | #用两个栈实现队列#
用两个栈实现队列
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.add(node);
}
public int pop() {
//将stack1里的数倒入stack2
while(!stack1.isEmpty()){
stack2.add(stack1.pop());
}
//stack2栈顶弹出的元素及队列的头元素
int r=stack2.pop();
//再把stack2里的数倒回给stack1
while(!stack2.isEmpty()){
stack1.add(stack2.pop());
}
return r;
}
}
查看20道真题和解析