using System;
namespace DataStructure
{
public class MyQueue<T>
{
private T[] _array;
private int _head;
private int _tail;
private int _size;
public MyQueue(int capacity)
{
if (capacity < 0)
throw new Exception("默認長度不可小於零");
this._array = new T[capacity];
this._head = 0;
this._tail = 0;
this._size = 0;
}
public int Count
{
get { return _size; }
}
public bool IsEmpty()
{
return _size == 0;
}
public void Clear()
{
if (this._head < this._tail)
{
Array.Clear(this._array, this._head, this._size);
}
else
{
Array.Clear(this._array, this._head, this._array.Length - this._head);
Array.Clear(this._array, 0, this._tail);
}
this._head = 0;
this._tail = 0;
this._size = 0;
}
public void Enqueue(T item)
{
if (this._size == this._array.Length)
{
int capacity = (int) ((long) this._array.Length * 200L / 100L);
if (capacity < this._array.Length + 4)
capacity = this._array.Length + 4;
this.SetCapacity(capacity);
}
this._array[this._tail] = item;
this._tail = (this._tail + 1) % this._array.Length;
++this._size;
}
public T Dequeue()
{
if (this._size == 0)
throw new Exception("隊列裏沒有數據了");
T obj = this._array[this._head];
this._array[this._head] = default(T);
this._head = (this._head + 1) % this._array.Length;
--this._size;
return obj;
}
public T Peek()
{
if (this._size == 0)
throw new Exception("隊列裏沒有數據了");
return this._array[this._head];
}
private void SetCapacity(int capacity)
{
T[] objArray = new T[capacity];
if (this._size > 0)
{
if (this._head < this._tail)
{
Array.Copy(this._array, this._head, objArray, 0, this._size);
}
else
{
Array.Copy(this._array, this._head, objArray, 0, this._array.Length - this._head);
Array.Copy(this._array, 0, objArray, this._array.Length - this._head, this._tail);
}
}
this._array = objArray;
this._head = 0;
this._tail = this._size == capacity ? 0 : this._size;
}
public bool Contains(T item)
{
int index = this._head;
int size = this._size;
while (size-- > 0)
{
if (item == null)
{
if (this._array[index] == null)
return true;
}
else if (this._array[index] != null && this._array[index].Equals(item))
return true;
index = (index + 1) % this._array.Length;
}
return false;
}
public void TrimExcess()
{
if (this._size >= (int) ((double) this._array.Length * 0.9))
return;
this.SetCapacity(this._size);
}
}
}