循環(huán)隊(duì)列不損失空間及C#實(shí)現(xiàn)

循環(huán)隊(duì)列損失空間

是因?yàn)殛?duì)列空時(shí)使用了font==rear的,隊(duì)列滿時(shí)則不能再使用,只能使得空出一位做判斷用(rear+1)%array.length=font
解決這一問題可以設(shè)置一個(gè)標(biāo)志位tag,tag=0表示空,tag=1表示滿。
當(dāng)入隊(duì)后rear=font時(shí),tag置為1;
當(dāng)出隊(duì)后font=rear時(shí),tag置為0;

實(shí)現(xiàn)

Queue

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FullQueue
{
    class Queue<T>
    {
        T[] queue;    //隊(duì)列數(shù)組
        int font;   //隊(duì)首
        int rear;   //隊(duì)尾
        int tag;    //標(biāo)志位,指示隊(duì)滿和隊(duì)空狀態(tài),0空 1滿

        public int Tag { get => tag; set => tag = value; }

        /// <summary>
        /// 構(gòu)造器
        /// </summary>
        public Queue(int length)
        {
            queue = new T[length];
            font = 0;
            rear = tag = font;
        }

        /// <summary>
        /// 入隊(duì)
        /// </summary>
        /// <param name="data"></param>
        public void Put(T data)
        {
            if (tag == 1) return;
            queue[rear] = data;
            rear = (rear + 1) % queue.Length;
            //隊(duì)滿狀態(tài)
            if (rear == font) tag = 1;
        }

        /// <summary>
        /// 出隊(duì)
        /// </summary>
        /// <returns></returns>
        public T Get()
        {
            if (tag == 0) return default(T);
            T tmp = queue[font];
            font = (font + 1) % queue.Length;
            //隊(duì)空狀態(tài)
            if (font == rear) tag = 0;
            return tmp;
        }
    }
}

Program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FullQueue
{
    class Program
    {
        static void Main(string[] args)
        {
            Queue<string> queue = new Queue<string>(5);
            queue.Put("a");
            queue.Put("b");
            queue.Put("c");
            queue.Put("d");
            queue.Put("e");
            queue.Put("f");

            while (queue.Tag != 0)
            {
                Console.WriteLine(queue.Get());
            }
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容