C# SequencedQueue.cs
适合初学者
算法与数据结构(C#)、C#、面向对象程序设计(C#)
public class SequencedQueue<T>
{
private T[] items;
private int front, rear; //front和rear为队列头尾的位置下标
//队列的初始化
public SequencedQueue(int n)
{
items = new T[n + 1];
front = rear = 0;
}
public SequencedQueue() : this(16) { }
public SequencedQueue(T[] a)
{
front = 0;
rear = a.Length;
items = new T[rear + 16 + 1];
for (int i = 0; i < rear; i++)
items[i] = a[i];
}
//返回队列中元素的个数
public int Count
{
get { return (rear - front + items.Length) % items.Length; }
}
//判断队列的状态是否为空和是否为满
public bool Empty { get { return front == rear; } }
public bool Full
{
get { return front == (rear + 1) % items.Length; }
}
//入队
public void Enqueue(T k)
{
if (Full) DoubleCapacity();
items[rear] = k;
rear = (rear + 1) % items.Length;
}
//扩充容量
private void DoubleCapacity()
{
int i, j;
int capacity = 2 * items.Length - 1;
int count = Count;
T[] copy = new T[capacity]; // 按照新容量构造一个数组
for (i = 0; i < count; i++)
{
j = (i + front) % items.Length;
copy[i] = items[j];
}
front = 0;
rear = count;
items = copy; // items 指向新分配的空间
}
//出队
public T Dequeue()
{
T k = default(T);
if (!Empty)
{ //队列不空
k = items[front]; //取得队头结点数据元素
front = (front + 1) % items.Length;
return k;
}
else //栈空时产生异常
throw new InvalidOperationException("Queue is Empty: " + this.GetType());
}
//获得队首,但不将其移除
public T Peek()
{
if (!Empty)
return items[front];
else
throw new InvalidOperationException("Queue is Empty: " + this.GetType());
}
//输出队列中所有数据元素的值
public void Show(bool showTypeName = false)
{
if (showTypeName)
Console.Write("Queue: ");
int i = this.front;
int n = i;
if (!Empty)
{
if (i < this.rear)
{
n = this.rear - 1;
}
else
{
n = this.rear + this.items.Length - 1;
}
for (; i <= n; i++)
{
Console.Write(items[i % items.Length] + " ");
}
}
Console.WriteLine();
}
//重写Tostring方法
public override string ToString()
{
StringBuilder s = new StringBuilder();
int i = this.front;
int n = i;
if (!Empty)
{
if (i < this.rear)
{
n = this.rear - 1;
}
else
{
n = this.rear + this.items.Length - 1;
}
}
for (; i <= n; i++)
{
s.Append(items[i % items.Length]);
s.Append(";");
}
return s.ToString();
}
public virtual T[] ToArray()//复制队列到一个新的数组中
{
T[] rv = new T[Count];
int j;
for (int i = 0; i < Count; i++)
{
j = (i + front) % items.Length;
rv[i] = items[j];
}
return rv;
}
// 查找k值在顺序队列中的位置,查找成功时返回k值首次出现位置,否则返回-1
public int IndexOf(T k)
{
int i = 0;
while (i < this.Count && !items[i].Equals(k))
i++;
if (i >= 0 && i < Count)
return i;
else return -1;
}
// 查找队列是否包含k值,查找成功时返回true,否则返回false
public bool Contains(T k)
{
int j = IndexOf(k);
if (j != -1)
return true;
else
return false;
}
}
不要吝啬你的赞哦o