顺序存储结构的循环队列

第一点:rear指向的是队尾的下一个元素
为了不让rear此时指向的是front 会留个空 让rear指向一个空位
第二点: 因为留了个空位 所以当你要插入k个元素的时候 你就要给这个顺寻存储结构数组长度设为K+1
第三点 :你在返回队尾 计算长度等等进行加减运算 的时候都要记得取模
在返回rear的时候我们知道 顺序循环队列的队尾是Rear-1 但是因为是循环我们不能保证现在的Rear是0还是几 一定要进行取模

class MyCircularQueue {
     int []queue;
    int front;
    int rear;
    int maxSize;
    /** Initialize your data structure here. Set the size of the queue to be k. */
    public MyCircularQueue(int k) {
       this.maxSize=k+1;
      this.front=0;
        this.rear=0;
     queue=new int[maxSize];
    }
    
    /** Insert an element into the circular queue. Return true if the operation is successful. */
    public boolean enQueue(int value) {
       if(isFull())
       {
           return false;
       }
       
            queue[rear]=value;
            rear=(rear+1)%maxSize;
            return true;
        
    }
    
    /** Delete an element from the circular queue. Return true if the operation is successful. */
    public boolean deQueue() {
     if(isEmpty())
     {
         return false;
     }
        
            front=(front+1)%maxSize;
            return true;
        
    }
    
    /** Get the front item from the queue. */
    public int Front() {
        if (isEmpty()){return -1;}
       return queue[front];
    }
    
    /** Get the last item from the queue. */
    public int Rear() {
         if (isEmpty()){return -1;}
       return queue[(rear-1+maxSize)%maxSize];
        }
    
    /** Checks whether the circular queue is empty or not. */
    public boolean isEmpty() {
        return front==rear;
    }
    
    /** Checks whether the circular queue is full or not. */
    public boolean isFull() {
      return front==(rear+1)%maxSize;
    }
}

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * MyCircularQueue obj = new MyCircularQueue(k);
 * boolean param_1 = obj.enQueue(value);
 * boolean param_2 = obj.deQueue();
 * int param_3 = obj.Front();
 * int param_4 = obj.Rear();
 * boolean param_5 = obj.isEmpty();
 * boolean param_6 = obj.isFull();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值