使用队列实现栈(2)(Java)

  1 class MyStack
  2 {
  3     private Queue q1;
  4     private Queue q2;
  5     
  6     public MyStack(int size)
  7     {
  8         this.q1 = new Queue(size);
  9         this.q2 = new Queue(size);
 10     }
 11     
 12     public boolean isFull()
 13     {
 14         return q1.isFull();
 15     }
 16     
 17     public boolean isEmpty()
 18     {
 19         return q1.isEmpty();
 20     }
 21     
 22     //时间复杂度: O(1)
 23     public void push(int k) throws Exception
 24     {
 25         if(this.q1.isFull())
 26             throw new Exception("Overflow.");
 27         else
 28             this.q1.EnQueue(k);
 29     }
 30     
 31     //时间复杂度: O(n)
 32     public int pop() throws Exception
 33     {
 34         if(this.q1.isEmpty())
 35             throw new Exception("Underflow.");
 36         else
 37         {
 38             for(int i = this.q1.getLength(); i > 1; i--)
 39                 this.q2.EnQueue(this.q1.DeQueue());
 40             int key = this.q1.DeQueue();
 41             while(!this.q2.isEmpty())
 42                 this.q1.EnQueue(this.q2.DeQueue());
 43             return key;
 44         }
 45     }
 46 }
 47 
 48 class Queue
 49 {
 50     private int front;
 51     private int rear;
 52     private int[] a;
 53     
 54     public Queue(int size)
 55     {
 56         this.front = this.rear = 0;
 57         this.a = new int[size];
 58     }
 59     
 60     public boolean isFull()
 61     {
 62         return (this.rear + 1) % this.a.length == this.front;
 63     }
 64     
 65     public boolean isEmpty()
 66     {
 67         return this.rear == this.front;
 68     }
 69     
 70     public void EnQueue(int k) throws Exception
 71     {
 72         //该判断是冗余的
 73         /*if(this.isFull())
 74          * 
 75             throw new Exception("Overflow.");*/
 76         //else
 77         {
 78             this.a[this.rear] = k;
 79             this.rear = (this.rear + 1) % this.a.length;
 80         }
 81             
 82     }
 83     
 84     public int DeQueue() throws Exception
 85     {
 86         //该判断是冗余的
 87         /*if(this.isEmpty())
 88             throw new Exception("Underflow.");*/
 89         //else
 90         {
 91             int key = this.a[front];
 92             this.front = (this.front + 1) % this.a.length;
 93             return key;
 94         }
 95     }
 96     
 97     public int getLength()
 98     {
 99         return (this.rear - this.front + this.a.length) % this.a.length;
100     }
101 }

 

转载于:https://www.cnblogs.com/Huayra/p/10690394.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值