题目链接
题目描述
用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。
栈的特性:先进入的后出来,后进入的先出来(First in last out)
队列的特性:先进来的先出去(First in first out)
想要利用两个栈实现队列的特性,我们不难想到:一个栈用来 push,时间复杂度为 O(1),pop 的时候将栈中元素全部 pop 到第二个栈中。然后再将第二个栈中的元素全部 pop 回第一个栈。时间复杂度为O(n)
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() {
if (stack1.isEmpty())
throw new RuntimeException();
while(!stack1.isEmpty()) {
int e = stack1.pop();
stack2.push(e);
}
int ret = stack2.pop();
while(!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
return ret;
}
}
我们发现,在pop()的时候,要两次将栈中所有元素出栈,未免有些麻烦。于是,我们想到,pop 的时候,我们先不急着将第二个栈中的元素全部 pop 回第一个栈,等到第二个栈为空之后,我们再将第一个栈中的元素全部pop到第二个栈
入栈 1, 2, 3
stack1
1 | 2 | 3 |
---|
stack2
出栈 1
stack1
stack2
3 | 2 |
---|
入栈 4, 5
stack1
4 | 5 |
---|
stack2
3 | 2 |
---|
出栈 2,3
stack1
4 | 5 |
---|
stack2
出栈 4
stack1
stack2
5 |
---|
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() {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}