/*
用一片連續的存儲空間來存儲隊列中的數據元素,這樣的隊列稱為順序隊列
(Sequence Queue)。類似於順序棧,在這里我就不做介紹了,我們直接用列表實現一個隊列
*/
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 數據結構Linked_List { public class LinkQueue<T> { private Node<T> front;//隊列頭指示器 internal Node<T> Front { get { return front; } set { front = value; } } private Node<T> rear;//隊列尾指示器 internal Node<T> Rear { get { return rear; } set { rear = value; } } private int nCount;//隊列結點個數 public int NCount { get { return nCount; } set { nCount = value; } } public LinkQueue() { front = rear = null; nCount = 0; } public int GetLength() { return nCount; } public void Clear() { front = rear = null; nCount = 0; } public bool IsEmpty() { if ( front == rear && 0 == nCount ) { return true; } return false; } public void Enqueue( T item ) { Node<T> p = new Node<T>(item); if ( IsEmpty() ) { front = rear = p;// 這步很重要 當第一個元素入隊的時候,必須給front賦值,否則front一直都是null } else { rear.Next = p; rear = p; } ++nCount; } public T Dqueue() { if ( IsEmpty() ) { Console.WriteLine("隊列為空"); return default(T); } Node<T> p = front;//從隊列頭出對 front = front.Next; if ( front == null ) { rear = null; } --nCount; return p.Data; } //獲取鏈隊列頭結點的值 public T GetFront() { if (IsEmpty()) { Console.WriteLine("隊列為空"); return default(T); } return front.Data; } } }
/*
隊列的應用舉例
編程判斷一個字符串是否是回文。回文是指一個字符序列以中間字符
為基准兩邊字符完全相同,如字符序列“ACBDEDBCA”是回文
*/
public static bool IsPalindromic() { SeqStack<char> stack = new SeqStack<char>(50); LinkQueue<char> queue = new LinkQueue<char>(); //string str = Console.ReadLine();// 這里隨便輸入 string str = "ACBDEDBCA";// 測試 for ( int i = 0; i < str.Length; ++i ) { stack.Push(str[i]); queue.Enqueue(str[i]); } bool flag = false; // 這里只需循環一半元素即可 for (int i = 0; i < str.Length >> 1; ++i ) { if (queue.Dqueue() == stack.Pop()) { flag = true; } else { flag = false; } } return flag; }
好了,今天就到這里了