05 用两个栈实现队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
1 import java.util.Stack; 2 import java.util.*; 3 //这道题果然是用 push和pop函数来当做队列的入队和出队 4 public class Solution { 5 //栈A用来作入队列 6 //栈B用来出队列,当栈B为空时,栈A全部出栈到栈B,栈B再出栈(即出队列) 7 Stack<Integer> stack1 = new Stack<Integer>(); 8 Stack<Integer> stack2 = new Stack<Integer>(); 9 10 public void push(int node) { 11 stack1.push(node); 12 } 13 14 public int pop() { 15 if(!stack2.empty()){ 16 return stack2.pop(); 17 }else{ 18 while( !stack1.empty()){ 19 stack2.push(stack1.pop()); 20 } 21 return stack2.pop(); 22 } 23 } 24 }
            
 
作者:shareidea            
 
出处:https://www.cnblogs.com/shareidea94/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。   
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号