C#算法从入门到跑路 第1章:线性表之双端队列

双端队列

EnterFront将元素插到队列头部 front- -
OutFront删除队列头部元素 front++
EnterRear将元素插到到队列尾部 rear++
OutRear删除队列尾部元素 rear- -

/// 
/// 循环双端队列
/// 
/// 数据类型
class CirDeque
{
    /// 
    /// 默认队列大小
    /// 
    private const int DEFAULT_SIZE = 10;
    /// 
    /// 数据域
    /// 
    private T[] data;
    /// 
    /// 队列头
    /// 
    private int front;
    /// 
    /// 队列尾巴
    /// 
    private int rear;
    /// 
    /// 判断队列满
    /// 
    /// 返回是否满
    public bool IsEmpty() => this.rear == this.front;
    /// 
    /// 判断队列满
    /// 
    /// 
    public void Expand()
    {
        if((this.rear + 1) % this.data.Length == this.front)
        {
            Array.Resize(ref this.data, 
                this.data.Length + this.data.Length << 1);
        }
    }
    /// 
    /// 构造器
    /// 
    /// 大小
    public CirDeque(int size=DEFAULT_SIZE)
    {
        this.data = new T[size];
        this.front = 0;
    }

    /// 
    /// 队头进队
    /// 
    /// 数据元素
    public void EnterFront(T val)
    {
        Expand();
        if(this.front==0)
        {
            this.front = this.data.Length - 1;
            this.data[this.front] = val;
        }
        else
        {
            this.front = (this.front - 1) % this.data.Length;
            this.data[this.front] = val;
        }
    }
    /// 
    /// 队尾进队
    /// 
    /// 数据元素
    public void EnterRear(T val)
    {
        Expand();
        this.data[this.rear] = val;
        this.rear = (this.rear + 1) % this.data.Length;
    }
    /// 
    /// 队头出队
    /// 
    /// 数据元素
    public T OutFront()
    {
        if(IsEmpty())
            throw new IndexOutOfRangeException("队空");
        var val= this.data[this.front];
        this.front = (this.front + 1) % this.data.Length;
        return val;
    }
    /// 
    /// 队尾出队
    /// 
    /// 数据元素
    public T OutRear()
    {
        if (IsEmpty())
            throw new IndexOutOfRangeException("队空");
        if(this.rear==0)
        {
            this.rear = this.data.Length - 1;
            return  this.data[this.rear];
        }
        else
        {
            this.rear = (this.rear - 1) % this.data.Length;
            return this.data[this.rear];
        }

    }
}

你可能感兴趣的:(c#,算法,队列)