队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(back)进行插入操作。进行插入操作的端称为队尾,进行删除操作的端称为队头。这也就是我们平常经常用说到的先进先出法则(FIFO),队列这种法则,在中国好久以前就开始运用了,例如粮仓管理官员,在没掌握这种法则前,仓库底部的粮食都因时间太久而坏掉了,后来有聪明人士在粮仓二边开个门,一边进仓一边出仓,这样管理就方便多了。队列中没有元素时,称为空队列。
队列实现的接口如下:
public interface IQueen<T>
{
int Length();
bool IsEmpty();
bool IsFull();
void Clear();
void IN(T items);
T Out();
T GetFrontItem();
}
队列实现的原理与代码如下:
Code
public class JQueen<T> : IQueen<T>
{
private int size;
private T[] item;
private int front;
private int back;
public JQueen()
: this(100)
{
size = 100;
item = new T[100];
front = back = -1;
}
public JQueen(int length)
{
size = length;
item = new T[length];
front = back = -1;
}
public T this[int index]
{
get { return item[index]; }
set { item[index] = value; }
}
public int Front
{
get { return front; }
set { front = value; }
}
public int Back
{
get { return back; }
set { back = value; }
}
public int MaxLength
{
get { return size; }
set { size = value; }
}
public int Length()
{
return (back - front + size) % size;
}
public bool IsEmpty()
{
return (front == back);
}
public bool IsFull()
{
return ((back + 1) % size == front);
}
public void Clear()
{
front = back = -1;
}
public void IN(T items)
{
if (IsFull())
{
throw new ArgumentOutOfRangeException("RangeException", "Queen RangeException: queen is full");
}
item[++back] = items;
}
public T Out()
{
T tmp = default(T);
if (IsEmpty())
{
throw new ArgumentOutOfRangeException("RangeException", "Queen RangeException: queen is empty");
}
tmp = item[++front];
return tmp;
}
public T GetFrontItem()
{
if (IsEmpty())
{
throw new ArgumentOutOfRangeException("RangeException", "Queen RangeException: queen is empty");
}
return item[front + 1];
}
} 测试队列代码:
Code
public class Program
{
static void Main(string[] args)
{
try
{
JQueen<string> JQ = new JQueen<string>();
Console.WriteLine(JQ.IsEmpty()); //是否为空
Console.WriteLine(JQ.IsFull()); //是否满队
Console.WriteLine(JQ.MaxLength); //初始化时队列的长度
Console.WriteLine(JQ.Length()); //队列元素长度
Console.WriteLine(JQ.Front); //队头位置
Console.WriteLine(JQ.Back); //队尾位置
JQ.IN("A"); //插入元素
JQ.IN("B");
JQ.IN("C");
JQ.IN("D");
Console.WriteLine(JQ.GetFrontItem()); //队头元素
Console.WriteLine("------元素出队后队头元素-------");
JQ.Out(); //出A
JQ.Out();
Console.WriteLine(JQ.GetFrontItem()); //出队二个元素后队头元素
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); //异常
Console.ReadLine();
}
}
}
结果如下: