隊列 隊列的概念是先進先出,這個應該不用多說了。看下面那個從網上找的現成圖片。

循環隊列 循環隊列在邏輯上將隊列中的數據擺成環形,如下圖:

下面直接上代碼。
隊列
隊列的概念是先進先出,這個應該不用多說了。看下面那個從網上找的現成圖片。
循環隊列
循環隊列在邏輯上將隊列中的數據擺成環形,如下圖:
下面直接上代碼。
[csharp] view plain copy 在CODE上查看代碼片派生到我的代碼片
/// <summary>
/// 循環隊列
/// 2015年1月4日
/// </summary>
/// <typeparam name="T"></typeparam>
public class MyCircleQueue<T>
{
/// <summary>
/// 隊列數組
/// </summary>
private T[] _queue;
/// <summary>
/// 隊首索引
/// </summary>
private int _front;
/// <summary>
/// 隊尾索引
/// </summary>
private int _rear;
/// <summary>
/// 隊列的內存大小,但實際可用大小為_capacity-1
/// </summary>
private int _capacity;
public MyCircleQueue(int queueSize)
{
if (queueSize < 1)
throw new IndexOutOfRangeException("傳入的隊列長度不能小於1。");
//設置隊列容量
_capacity = queueSize;
//創建隊列數組
_queue = new T[queueSize];
//初始化隊首和隊尾索引
_front = _rear = 0;
}
/// <summary>
/// 添加一個元素
/// </summary>
/// <param name="item"></param>
public void Push(T item)
{
//隊列已滿
if (GetNextRearIndex() == _front)
{
//擴大數組
T[] newQueue = new T[2 * _capacity];
if (newQueue == null)
throw new ArgumentOutOfRangeException("數據容量過大,超出系統內存大小。");
//隊列索引尚未回繞
if (_front == 0)
{
//將舊隊列數組數據轉移到新隊列數組中
Array.Copy(_queue, newQueue, _capacity);
}
else
{
//如果隊列回繞,剛需拷貝再次,
//第一次將隊首至舊隊列數組最大長度的數據拷貝到新隊列數組中
Array.Copy(_queue, _front, newQueue, _front, _capacity - _rear - 1);
//第二次將舊隊列數組起始位置至隊尾的數據拷貝到新隊列數組中
Array.Copy(_queue, 0, newQueue, _capacity, _rear + 1);
//將隊尾索引改為新隊列數組的索引
_rear = _capacity + 1;
}
_queue = newQueue;
_capacity *= 2;
}
//累加隊尾索引,並添加當前項
_rear = GetNextRearIndex();
_queue[_rear] = item;
}
/// <summary>
/// 獲取隊首元素
/// </summary>
/// <returns></returns>
public T FrontItem()
{
if (IsEmpty())
throw new ArgumentOutOfRangeException("隊列為空。");
return _queue[GetNextFrontIndex()];
}
/// <summary>
/// 獲取隊尾元素
/// </summary>
/// <returns></returns>
public T RearItem()
{
if (IsEmpty())
throw new ArgumentOutOfRangeException("隊列為空。");
return _queue[_rear];
}
/// <summary>
/// 彈出一個元素
/// </summary>
/// <returns></returns>
public T Pop()
{
if (IsEmpty())
throw new ArgumentOutOfRangeException("隊列為空。");
_front = GetNextFrontIndex();
return _queue[_front];
}
/// <summary>
/// 隊列是否為空
/// </summary>
/// <returns></returns>
public bool IsEmpty()
{
return _front == _rear;
}
/// <summary>
/// 獲取下一個索引
/// </summary>
/// <returns></returns>
private int GetNextRearIndex()
{
if (_rear + 1 == _capacity)
{
return 0;
}
return _rear + 1;
}
/// <summary>
/// 獲取下一個索引
/// </summary>
/// <returns></returns>
private int GetNextFrontIndex()
{
if (_front + 1 == _capacity)
{
return 0;
}
return _front + 1;
}
}
