循環(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());
}
}
}
}