首页 > 其他 > 详细

面试题9-用两个栈来实现一个队列,完成队列的Push和Pop操作

时间:2018-10-21 23:12:01      阅读:170      评论:0      收藏:0      [点我收藏+]
  • 题目
    • 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
  • 思路:
    • 一个栈压入元素,而另一个栈作为缓冲,将栈1的元素出栈后压入栈2中
  • 代码 
import java.util.Stack;
/**
 *两个栈实现一个队列
 * @author MSI
 */
public class Requeue{
     Stack<Integer> sk1=new Stack<Integer>();
     Stack<Integer> sk2=new Stack<Integer>();
     public void push(int val){
         sk1.push(val);
     }
     public int pop()throws Exception{//将栈1依次出栈,并压入栈2
         if(sk1.isEmpty()&&sk2==null){
             throw new Exception("queue is empty");
         }
         while(sk2.isEmpty()){
             while(!sk1.isEmpty()){
                 sk2.push(sk1.pop());
             }
         }
         return sk2.pop();
     }
    public static void main(String Args[]) throws Exception{
        Requeue q1=new Requeue();
        q1.push(1);
        q1.push(2);
        q1.push(3);
        while(q1!=null)
        System.out.println(q1.pop());       
        }
    }
  • 输出
  • 1
    2
    3
    

      

面试题9-用两个栈来实现一个队列,完成队列的Push和Pop操作

原文:https://www.cnblogs.com/moonlightml/p/9827555.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!