环形队列的应用

/// <summary>
    /// 环形队列
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class CircleQueue<T>
    {
        private T[] queue;
        private int length;
        private int capacity;
        /// <summary>
        /// 头部
        /// </summary>
        private int head = 0;
        /// <summary>
        /// 尾部
        /// </summary>
        private int tail = 0;

        public CircleQueue(int capacity)
        {
            this.capacity = capacity;
            this.length = 0;
            this.head = 0;
            this.tail = 0;
            this.queue = new T[capacity];
        }
        /// <summary>
        /// 清空
        /// </summary>
        public void Clear()
        {
            head = 0;
            tail = 0;
            length = 0;
            this.queue = new T[this.capacity];
        }
        /// <summary>
        /// 队列是否为空
        /// </summary>
        /// <returns></returns>
        public bool IsEmpty()
        {
            return length == 0;
        }
        /// <summary>
        /// 队列是否已满
        /// </summary>
        /// <returns></returns>
        public bool IsFull()
        {
            return length == capacity;
        }
        /// <summary>
        /// 队列长度
        /// </summary>
        /// <returns></returns>
        public int Length()
        {
            return length;
        }
        /// <summary>
        /// 获取队列
        /// </summary>
        /// <returns></returns>
        public T[] GetAllQueue()
        {
            return queue;
        }
        /// <summary>
        /// 插入队列
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public bool EnQueue(T node)
        {
            if (IsFull() == false)
            {
                queue[tail] = node;
                tail = (++tail) % capacity;
                length++;
                return true;
            }
            return false;
        }
        /// <summary>
        /// 获取队列第一个元素
        /// </summary>
        /// <returns></returns>
        public T DeQueue()
        {
            T node = default(T);
            if (IsEmpty() == false)
            {
                node = queue[head];
                head = (++head) % capacity;
                length--;
            }
            return node;
        }
        /// <summary>
        /// 显示剩余数据
        /// </summary>
        public void ShowItems()
        {
            for (int i = head; i < length + head; i++)
            {
                Console.WriteLine(queue[i % capacity]);
            }
        }
    }//end

环形队列主要应用在单线程读或者写,无需要锁,相比较Queue队列,Queue队列可能会出现单个元素的时候又读又写造成死锁。

转载于:https://www.cnblogs.com/hcfan/p/7894891.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值