用两个栈实现队列之程序员面试经典

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

比如有栈A和栈B,在模拟队列的时候先将所有数据依次放入栈A中,在要弹出的时候将A中的数据依次从上到下放进栈B,结束之后取出B中最上面的那个数据,然后从上到下将数据放进栈A中,这样就用两个栈来实现了一个队列的“先进先出”的特点,而栈的特点是“后进先出”

代码如下:

  1. Stack<Integer> stack1 = new Stack<Integer>();  
  2.     Stack<Integer> stack2 = new Stack<Integer>();  
  3.       
  4.     public void push(int node) {  
  5.          stack1.push(node);  
  6.     }  
  7.       
  8.     public int pop() {       
  9.         while(!stack1.isEmpty()){  
  10.         stack2.push(stack1.pop());         
  11.         }  
  12.       
  13.     int aaa=stack2.pop();  
  14.             while(!stack2.isEmpty()){  
  15.             stack1.push(stack2.pop());  
  16.             }     
  17.             return aaa;  
  18.     }  

你可能感兴趣的:(用两个栈实现队列之程序员面试经典)