环形队列的应用

Posted 点点_滴滴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了环形队列的应用相关的知识,希望对你有一定的参考价值。

/// <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队列可能会出现单个元素的时候又读又写造成死锁。

以上是关于环形队列的应用的主要内容,如果未能解决你的问题,请参考以下文章

环形队列-高效定时触发

Java数据结构 -- 环形队列 & 数组模拟环形队列

java数据结构与算法:单向队列与环形队列详解(图片+代码)

channel原来就是个环形队列

循环队列原理及在单片机串口通讯的应用

裸机中环形队列与RTOS中消息队列的区别