核心思想:利用求余,让索引循环
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;
}
}
}