隊列是一種特殊的線性表,它只允許在表的前端(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()); //是否滿隊
&n