標籤:
/*
用一片連續的儲存空間來儲存隊列中的資料元素,這樣的隊列稱為順序隊列
(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; }
好了,今天就到這裡了
c#隊列的實現