欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode - 设计循环双端队列

程序员文章站 2024-03-08 19:26:10
...

Leetcode - 设计循环双端队列Leetcode - 设计循环双端队列

public class MyCircularDeque {
    public int[] dataset;
    public int pfront;
    public int prear;
    public int maxsize;

    /** Initialize your data structure here. Set the size of the deque to be k. */
    public MyCircularDeque(int k) {
        dataset=new int[k+1];
        maxsize=k+1;
        pfront=prear=0;

    }

    /** Checks whether the circular deque is full or not. */
    public bool IsFull()
    {
        return ((prear+1)%maxsize==pfront);
    }

    /** Checks whether the circular deque is empty or not. */
    public bool IsEmpty()
    {
        return (pfront==prear);
    }

    /** Adds an item at the front of Deque. Return true if the operation is successful. */
    public bool InsertFront(int value) {
        if(IsFull())
        return false;
        pfront=(pfront+maxsize-1)%maxsize;
        dataset[pfront]=value;
        return true;

    }
    
    /** Adds an item at the rear of Deque. Return true if the operation is successful. */
    public bool InsertLast(int value) {
        if(IsFull())
        return false;
        dataset[prear]=value;
        prear=(prear+1)%maxsize;
        return true;

    }
    
    /** Deletes an item from the front of Deque. Return true if the operation is successful. */
    public bool DeleteFront() {
        if(IsEmpty())
        return false;
        pfront=(pfront+1)%maxsize;
        return true;

    }
    
    /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
    public bool DeleteLast() {
        if(IsEmpty())
        return false;
        prear=(prear-1+maxsize)%maxsize;
        return true;

    }
    
    /** Get the front item from the deque. */
    public int GetFront() {
        if(IsEmpty())
        return -1;
        return dataset[pfront];

    }
    
    /** Get the last item from the deque. */
    public int GetRear() {
        if(IsEmpty())
        return -1;
        return dataset[(prear-1+maxsize)%maxsize];
    }
}

/**
 * Your MyCircularDeque object will be instantiated and called as such:
 * MyCircularDeque obj = new MyCircularDeque(k);
 * bool param_1 = obj.InsertFront(value);
 * bool param_2 = obj.InsertLast(value);
 * bool param_3 = obj.DeleteFront();
 * bool param_4 = obj.DeleteLast();
 * int param_5 = obj.GetFront();
 * int param_6 = obj.GetRear();
 * bool param_7 = obj.IsEmpty();
 * bool param_8 = obj.IsFull();
 */

Leetcode - 设计循环双端队列

相关标签: Leetcode练习