题解 | #用两个栈实现队列#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
思路:
- 两个栈,一个正序,一个反序
- 反序的非空可以直接pop()
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() {
//其中一个维持正序,另一个非空时维持反序
//s2反序栈,相当于队列头顺序
if(!stack2.isEmpty()){
return stack2.pop();
}
//s1非空,s2为空,将s1中的反序添加到s2,s2中相当于反序,则为队列
if(!stack1.isEmpty() && stack2.isEmpty()){
while(!stack1.isEmpty()){
int temp = stack1.pop();
stack2.push(temp);
}
return stack2.pop();
}
return -1;
}
}
查看3道真题和解析