leetcode探索队列和栈(一)

对于队列,我们可以使用动态数组和指向队列头部的索引来实现,当队列数据较多时,数组的容量要求较大,一种比较好的改进方法使用数组实现循环队列。

我们来看一下leetcode给出的演示:

leetcode探索队列和栈(一)_第1张图片leetcode探索队列和栈(一)_第2张图片

可以得出:

队列满时:(tail+1)%length == head       length为长度

队列为空:head==tail 

循环队列的方法:

  • MyCircularQueue(k): 构造器,设置队列长度为 k 。
  • Front: 从队首获取元素。如果队列为空,返回 -1 。
  • Rear: 获取队尾元素。如果队列为空,返回 -1 。
  • enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
  • deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
  • isEmpty(): 检查循环队列是否为空。
  • isFull(): 检查循环队列是否已满。

代码:

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

参考:https://blog.csdn.net/ws948342046/article/details/87893512

你可能感兴趣的:(LeetCode)