c# 環形佇列
阿新 • • 發佈:2018-11-28
核心思想:利用求餘,讓索引迴圈
class CircularQueue<T>
{
private T[] _queue;
private int _head;
private int _tail;
private int _count;
private int _capacity;
public int Count
{
get
{
return _count;
//return (_head - _tail + _capacity) % _capacity;不用計數器得到長度的方法
}
}
public int Capacity
{
get { return _capacity; }
}
public CircularQueue(int capacity)
{
_capacity = capacity;
_queue = new T[_capacity];
_head = 0;
_tail = 0;
_count = 0 ;
}
public bool IsFull()
{
return _count == _capacity;
//return _head == (_tail + 1)%_capacity;不用計數器實現判滿的方法,需要犧牲一個空間
}
public bool IsEmpty()
{
return _count == 0;
//return _head == _tail;不用計數器實現判空的方法
}
public void Enquene(T item)
{
if (IsFull())
{
Console.WriteLine("Queue is Full!");
return;
}
_queue[_tail] = item;
_tail = (_tail + 1) % _capacity;
_count++;
}
public T Dequeue()
{
if (IsEmpty())
{
Console.WriteLine("Queue is Full!");
return default(T);
}
T temp = _queue[_head];
_head = (_head + 1) % _capacity;
_count--;
return temp;
}
public T Peek()
{
if (IsEmpty())
{
Console.WriteLine("Queue is Full!");
return default(T);
}
return _queue[_head];
}
public void Clear()
{
Array.Clear(_queue, 0, _capacity);
_head = 0;
_tail = 0;
_count = 0;
}
public bool Contains(T item)
{
int index = _head;
for (int i = 0; i < _count; i++)
{
if (item.Equals(_queue[index]))
{
return true;
}
index = (index + 1) % _capacity;
}
return false;
}
public void DisPlay()
{
int index = _head;
for (int i = 0; i < _count; i++)
{
Console.WriteLine(_queue[index]);
index = (index + 1) % _capacity;
}
}
}