以《資料結構》學習筆記(二)中JavaScript程式碼實現的棧操作執行個體為範例用C#語言編程重寫:
Stack s = new Stack();s.Push(1);s.Push(2);s.Push(2);s.Push(2);s.Push(null);object b = s.Pop();Console.WriteLine("s 的Pop方法: " + b);foreach(int j in s){Console.WriteLine("s: " + j);}s.Push(3);foreach(int k in s){Console.WriteLine("Push方法後的 s: " + k);}
隊列操作執行個體:
Queue s = new Queue();s.Enqueue(1);s.Enqueue(2);s.Enqueue(2);s.Enqueue(2);object b = s.Dequeue();Console.WriteLine("s 的Dequeue方法: " + b);foreach(int j in s){Console.WriteLine("s: " + j);}s.Enqueue(3);foreach(int k in s){Console.WriteLine("Enqueue方法後的 s: " + k);}
注:Stack類、Queue類都位於System.Collections中。
上面的重寫可以說明Push()方法和Pop()方法是棧(Stack)的兩個重要操作,與之對應的隊列(Queue)的兩個操作分別為Enqueue()方法和Dequeue()方法。接下來,用C#編程實現在《資料結構》3.2節:棧的應用舉例
3.2.1 數制轉換
void conversion(){ //構造空棧 Stack s = new Stack(); int n; int result; Int32.TryParse(Console.ReadLine(), out result); n = result; while (n != 0) { s.Push(n % 8); n = n / 8; } while (s.Count != 0) { object e = s.Pop(); Console.Write(e); }}
下面是泛型程式設計實現的完整程式碼:
using System;using System.Collections.Generic;class StackDemo{ static void conversion() { //構造空棧 Stack<int> s = new Stack<int>(); int n; int result; Int32.TryParse(Console.ReadLine(), out result); n = result; while (n != 0) { s.Push(n % 8); n = n / 8; } while (s.Count != 0) { int e = s.Pop(); Console.Write(e); } } static void Main(string[] args) { conversion(); }}
3.2.3 行編輯程式 書上是用棧實現,在這兒本人用JavaScript語言編程實現如下:
for(i=0;i<ch.length;i++){ if(tb1.value.length > 0 && ch[i] != '\n') { switch(ch[i]) { case '#': list.pop(); break; case '@': list = []; break; default: list.push(ch[i]); break; } }}alert(list.join(''));
上面的代碼是在網頁上的文字框輸入多行文本,點擊提交按鈕出現程式處理後的內容。下面的代碼是用C#語言編程樣本。
Stack<char> s = new Stack<char>();char[] ch = new char[tb1.Text.Length];ch = tb1.Text.ToCharArray();for (int i = 0; i < ch.Length; i++){ if (tb1.Text.Length > 0 && ch[i] != '\n') { switch (ch[i]) { case '#': s.Pop(); break; case '@': s.Clear(); break; default: s.Push(ch[i]); break; } }}List<char> ch2 = new List<char>();IEnumerator enu = s.GetEnumerator();while(enu.MoveNext()){ ch2.Add(char.Parse(enu.Current.ToString()));}string sb = "";foreach (char c in ch2){ sb = sb.Insert(0, c.ToString());}Response.Write(sb);s.Clear();
在上面的代碼看後面的暴值是採用得到一個IEnumerator對象的方式訪問,這樣訪問的好處不用把它們從棧中彈出(即Pop()操作方法)。
我們來看看漢諾(Hanoi)塔遊戲: http://chemeng.p.lodz.pl/zylla/games/hanoi3e.html
下面是C#編程實現3.3節漢諾塔問題的程式碼:
using System;class Program{ //計數 static int count = 0; static void move(byte n, char x, char y) { Console.WriteLine("將 {0} 號從 {1} 移到 {2}", n, x, y); } //Hanoi 方法 static void Hanoi(byte n, char x, char y, char z) { if (n == 1) { ++count; //將編號為1的圓盤從x移到z move(n, x, z); } else { ++count; //將x上編號為1至n-1的圓盤移到y,z作中間塔 Hanoi((byte)(n - 1), x, z, y); //將編號為n的圓盤從x移到z move(n, x, z); //將y上編號為1至n-1的圓盤移到z,x作中間塔 Hanoi((byte)(n - 1), y, x ,z); } } static void Main(string[] args) { //n為3時 Hanoi(3, 'x', 'y', 'z'); Console.WriteLine(count); }}