题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路
队列是先进先出。栈是先进后出。所以push的时候可以直接放入到栈1的顶部,pop时将栈1的数据转移到栈2,此时栈顶的数问最先进入的数,取出,然后再将栈2的数据转回到栈1。保证栈1的顶部是最后进来的数字。
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() {
while(!stack1.empty())
stack2.push(stack1.pop());
int x = stack2.peek();
stack2.pop();
while(!stack2.empty())
stack1.push(stack2.pop());
return x;
}
}
自己出现的问题
栈的peek操作只读取栈顶数据,而不读出。pop操作读取栈顶数据并读出。