列的操作原则是先进先出的,所以队列又称作FIFO表(First In First Out)
队列的基本运算也有六种:
置空队 :InitQueue(Q)
判队空: QueueEmpty(Q)
判队满: QueueFull(Q)
入队 : EnQueue(Q,x)
出队 : DeQueue(Q)
取队头元素: QueueFront(Q),不同与出队,队头元素仍然保留
namespace Queue
{
/// <summary>
/// Implement Queue in Array.
/// </summary>
class Queue
{
private int[] items;
private int count;
/// <summary>
/// Initial Queue.
/// </summary>
/// <param name="capability"></param>
public Queue(int capability)
{
//capability should always bigger than 0.
if (capability > 0)
items = new int[capability];
else
throw new IndexOutOfRangeException("Array should be more than 0.");
this.count = 0;
}
/// <summary>
/// Add Item at the end of Queue.
/// </summary>
/// <param name="item"></param>
public void EnQueue(int item)
{
MoveAllNext();
items[0] = item;
this.count++;
}
/// <summary>
/// Delete item at the front of Queue.
/// Return the deleted item of Queue.
/// </summary>
/// <returns></returns>
public int DeQueue()
{
int temp = items[count - 1];
items[count - 1] = 0;
count--;
return temp;
}
/// <summary>
/// Return the front item of Queue without deleting.
/// </summary>
/// <returns></returns>
public int Peek()
{
if (count > 0 && count <= items.Length)
return items[count - 1];
else
throw new IndexOutOfRangeException("Count is out of Array Range.");
}
/// <summary>
/// If Queue is Full, return true.
/// </summary>
/// <returns></returns>
public bool IsFull()
{
return this.count == items.Length ? true : false;
}
/// <summary>
/// If Queue is Empty, return true.
/// </summary>
/// <returns></returns>
public bool IsEmpty()
{
return this.count == 0 ? true : false; ;
}
/// <summary>
/// Move All Items in Array to next sequently.
/// the last element in Array will move out of Array.
/// </summary>
private void MoveAllNext()
{
if (count == 0)
return;
else if (count > 0 && count <= items.Length)
{
int[] temp = new int[items.Length];
temp[0] = 0;
for (int i = 1; i < count; i++)
{
temp[i] = items[i - 1];
}
items = temp;
}
else
throw new IndexOutOfRangeException("Count is out of Array Range.");
}
/// <summary>
/// Move All Items in Array to front sequently.
/// the original element in Array will be over writed.
/// </summary>
private void MoveAllFront()
{
if (count == 0)
return;
else if (count > 0 && count <= items.Length)
{
int[] temp = new int[items.Length];
for (int i = 1; i < count; i++)
{
temp[i - 1] = items[i];
}
items = temp;
}
else
throw new IndexOutOfRangeException("Count is out of Array Range.");
}
}
}