C#实现队列,能实现循环队列,缺点是可用长度比声明的长度少1。
代码:
/// <summary> /// 队列 /// </summary> public class Queue { private object[] data; //用数组data来存储数据 protected int length; protected int head; //头指针 protected int tail; //尾指针 public int Length { get { return this.length; } //可读不可写 } public object this[int index] { get { return this.data[index]; } } public Queue(int size) { data = new object[size]; length = size; head = 0; //头指针赋0 tail = 0; //尾指针赋0 } /// <summary> /// Queue 是否空 /// </summary> /// <returns></returns> public bool isEmpty() { return head == tail; } /// <summary> /// Queue 是否满 /// </summary> /// <returns></returns> public bool isFull() { return this.length == 0 || (this.tail + 1) % this.length == this.head; } /// <summary> /// 进队列 /// </summary> /// <param name="elem"></param> public void Push(object elem) { if (this.isFull()) { throw new Exception("Queue is already full!"); } this.data[this.tail] = elem; tail = (tail + 1) % this.length; } /// <summary> /// 出队列 /// </summary> /// <returns></returns> public object Pull() { if (this.isEmpty()) { throw new Exception("Queue is empty!"); } object element =this.data[this.head]; head = (this.head + 1) % this.length; return element; } /// <summary> /// 获取头元素 /// </summary> /// <returns></returns> public object getHeadElement() { if (this.isEmpty()) { throw new Exception("Queue is empty!"); } return this.data[head]; } /// <summary> /// 获取尾元素 /// </summary> /// <returns></returns> public object getTailElement() { if (this.isEmpty()) { throw new Exception("Queue is empty!"); } int loc = this.tail == 0 ? this.length - 1 : (this.tail - 1) % this.length; return this.data[loc]; } /// <summary> /// 清空队列 /// </summary> public void Clear() { this.head = this.tail = 0; } }