题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:想通了不难,push操作用第一个Stack正常进行。而pop操作则先把Stack1倒入Stack2,再取出。
第一版代码:
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 node;
while (!stack1.empty()){
stack2.push(stack1.pop());
}
node = stack2.pop();
while (!stack2.empty()){
stack1.push(stack2.pop());
}
return node;
}
}
看到了一种更好的方法,再pop操作判断stack2是否为空,不为空则直接取出stack2的top,这样可以不用重复倒入倒出,节省资源,学习学习。
更好的pop()方法:
public int pop() {
int node;
if (stack2.empty()) {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
}
node = stack2.pop();
return node;
}