美文网首页
循环队列不损失空间及C#实现

循环队列不损失空间及C#实现

作者: 周末的游戏之旅 | 来源:发表于2019-08-03 10:31 被阅读0次

循环队列损失空间

是因为队列空时使用了font==rear的,队列满时则不能再使用,只能使得空出一位做判断用(rear+1)%array.length=font
解决这一问题可以设置一个标志位tag,tag=0表示空,tag=1表示满。
当入队后rear=font时,tag置为1;
当出队后font=rear时,tag置为0;

实现

Queue

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

namespace FullQueue
{
    class Queue<T>
    {
        T[] queue;    //队列数组
        int font;   //队首
        int rear;   //队尾
        int tag;    //标志位,指示队满和队空状态,0空 1满

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

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

        /// <summary>
        /// 入队
        /// </summary>
        /// <param name="data"></param>
        public void Put(T data)
        {
            if (tag == 1) return;
            queue[rear] = data;
            rear = (rear + 1) % queue.Length;
            //队满状态
            if (rear == font) tag = 1;
        }

        /// <summary>
        /// 出队
        /// </summary>
        /// <returns></returns>
        public T Get()
        {
            if (tag == 0) return default(T);
            T tmp = queue[font];
            font = (font + 1) % queue.Length;
            //队空状态
            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());
            }
        }
    }
}

相关文章

网友评论

      本文标题:循环队列不损失空间及C#实现

      本文链接:https://www.haomeiwen.com/subject/qgzddctx.html