使用单链表实现队列。
front和rear分别表示队列的队头结点和队尾结点。其实并没有必要设置队尾结点这一属性,比如,在实现单链表的时候,并没有加入一个rear的属性,但是加入rear属性的好处在于,避免每次查到尾部元素或者在尾部添加新的元素时,遍历一遍所有的结点,因而单链表的实现实际上也可以做出相同的改进。本质上属于以空间换时间的策略。
队列接口:
//队列接口 interface IQueueDs<T> { int GetLength(); bool IsEmpty(); bool IsFull(); void In(T t); T Out(); T GetFront(); }
链队列的结点类:
//链队列的结点类 class Node<T> { private T tVal; private Node<T> nNext; public T Val { get { return this.tVal; } set { this.tVal = value; } } public Node<T> Next { get { return this.nNext; } set { this.nNext = value; } } public Node() { this.tVal = default(T); this.nNext = null; } public Node(T t) { this.tVal = t; this.nNext = null; } }
链队列类:
//链队列类 class LinkedQueue<T>:IQueueDs<T> { private Node<T> nFront; private Node<T> nRear;//以空间换时间的策略 private int intNum; public Node<T> Front { get { return this.nFront; } set { this.nFront = value; } } public Node<T> Rear { get { return this.nRear; } set { this.nRear = value; } } public int Num { get { return this.intNum; } set { this.intNum = value; } } public LinkedQueue() { this.nFront = null; this.nRear = null; this.intNum = 0; } public LinkedQueue(T t) { Node<T> node = new Node<T>(t); this.nFront = node; this.nRear = node; this.intNum = 1; } #region IQueueDs<T> 成员 public int GetLength() { return this.intNum; } public bool IsEmpty() { return this.intNum == 0; } public bool IsFull() { Console.WriteLine("No limit for LinkedQueue!"); return false; } public void In(T t) { Node<T> node = new Node<T>(t); if (this.IsEmpty()) { this.nFront = node; this.nRear = node; this.intNum++; return; } this.nRear.Next = node; this.nRear = node; this.intNum++; } public T Out() { if (this.IsEmpty()) { Console.WriteLine("No more elements!"); return default(T); } else { Node<T> node = this.nFront; this.nFront = node.Next; this.intNum--; return node.Val; } } public T GetFront() { if (!this.IsEmpty()) { return this.nFront.Val; } else { Console.WriteLine("The queue has no elements!"); return default(T); } } #endregion }