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


  1. import java.util.Stack;  
  2.    
  3. public class Solution {  
  4.    Stack<Integer> stack1 = new Stack<Integer>();  //当做主队列
  5.    Stack<Integer> stack2 = new Stack<Integer>();  //当做辅助
  6.      
  7. //入栈函数  
  8.    public void push(int num) {  
  9.        stack1.push(num);    //直接用栈的push方法       
  10.     }  
  11.      
  12. //出栈函数  
  13.    public int pop() {  
  14.    Integer re=null;   
  15.        if(!stack2.empty()){  // 如果栈2不是空的,那么把最上面那个取出来  
  16.            re=stack2.pop();   
  17.        }else{   
  18.                //如果栈2是空的,就把栈1里的数一个个取出来,放到栈2里  
  19.            while(!stack1.empty()){     
  20.                 re=stack1.pop();   
  21.                 stack2.push(re);   
  22.                              }   
  23.                   //栈2里有数之后,再次把里面的数取出来  
  24.                   if(!stack2.empty()){   
  25.                          re=stack2.pop();   
  26.                    }   
  27.        }   
  28.        return re;   
  29.     }  
  30. }  

猜你喜欢

转载自blog.csdn.net/boguesfei/article/details/80530919