题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
比如有栈A和栈B,在模拟队列的时候先将所有数据依次放入栈A中,在要弹出的时候将A中的数据依次从上到下放进栈B,结束之后取出B中最上面的那个数据,然后从上到下将数据放进栈A中,这样就用两个栈来实现了一个队列的“先进先出”的特点,而栈的特点是“后进先出”
代码如下:
- 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.isEmpty()){
- stack2.push(stack1.pop());
- }
- int aaa=stack2.pop();
- while(!stack2.isEmpty()){
- stack1.push(stack2.pop());
- }
- return aaa;
- }