zoukankan      html  css  js  c++  java
  • 面试题9-用两个栈来实现一个队列,完成队列的Push和Pop操作

    • 题目
      • 用两个栈来实现一个队列,完成队列的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
      

        

  • 相关阅读:
    关于 下载 nfs-utils时的 gssproxy conflicts with selinux-policy-3.13.1-102.el7.noarch 错误
    SCP命令
    DHCP服务
    NFS服务
    ssh免密登录
    可见性判断
    (八)图像处理
    (八)图像处理
    (八)Grahpics之Blit
    (七)时间动画_Time
  • 原文地址:https://www.cnblogs.com/moonlightml/p/9827555.html
Copyright © 2011-2022 走看看