C#界說並完成單鏈表實例解析。本站提示廣大學習愛好者:(C#界說並完成單鏈表實例解析)文章只能為提供參考,不一定能成為您想要的結果。以下是C#界說並完成單鏈表實例解析正文
本文以實例具體描寫了C#界說並完成單鏈表的進程及道理。普通來講C#界說並完成單鏈表,代碼包含組成鏈表的結點界說、用變量來完成表頭、清空全部鏈表 、鏈表復位,使第一個結點成為以後結點、斷定鏈表能否為空、斷定以後結點能否為最初一個結點、前往以後結點的下一個結點的值,並使其成為以後結點、將以後結點移出鏈表,下一個結點成為以後結點等外容。
詳細完成代碼以下所示:
using System; using System.IO; // 組成鏈表的結點界說 public class Node { public Object data; public Node next; public Node( Object d ) { data = d; next = null; } } public class List { // 用變量來完成表頭 private Node Head = null; private Node Tail = null; private Node Pointer = null; private int Length = 0; //清空全部鏈表 public void deleteAll( ) { Head = null; Tail = null; Pointer = null; Length = 0; } //鏈表復位,使第一個結點 成為以後結點 public void reset( ) { Pointer = null; } //斷定鏈表能否為空 public bool isEmpty( ) { return (Length == 0); } //斷定以後結點能否 為最初一個結點 public bool isEnd( ) { if (Length == 0) throw new System.Exception( ); else if (Length == 1) return true; else return (cursor( ) == Tail); } //前往以後結點的下一個結點的值, 並使其成為以後結點 public Object nextNode( ) { if (Length == 1) throw new System.Exception( ); else if (Length == 0) throw new System.Exception( ); else { Node temp = cursor(); Pointer = temp; if (temp != Tail) return (temp.next.data); else throw new System.Exception( ); } } //前往以後結點的值 public Object currentNode( ) { Node temp = cursor( ); return temp.data; } //在以後結點前拔出一個結點, 並使其成為以後結點 public void insert( Object d ) { Node e = new Node( d ); if (Length == 0) { Tail = e; Head = e; } else { Node temp = cursor( ); e.next = temp; if (Pointer == null) Head = e; else Pointer.next = e; } Length++; } //前往鏈表的年夜小 public int size( ) { return Length; } //將以後結點移出鏈表,下一個結點成為以後結點 //假如移出的結點是最初一個結點,則第一個結點成為以後結點 public Object remove( ) { Object temp; if (Length == 0) throw new System.Exception( ); else if (Length == 1) { temp = Head.data; deleteAll( ); } else { Node cur = cursor( ); temp = cur.data; if (cur == Head) Head = cur.next; else if (cur == Tail) { Pointer.next = null; Tail = Pointer; reset( ); } else Pointer.next = cur.next; Length--; } return temp; } //前往以後結點的指針 private Node cursor( ) { if (Head == null) throw new System.Exception( ); else if (Pointer == null) return Head; else return Pointer.next; } //鏈表的簡略運用舉例 public static void Main( ) { List a = new List(); for (int i = 1; i <= 10; i++) a.insert( new IntPtr(i)); Console.WriteLine(a.currentNode( )); while (!a.isEnd( )) Console.WriteLine(a.nextNode( )); a.reset(); while (!a.isEnd( )) { a.remove( ); } a.remove( ); a.reset( ); if (a.isEmpty( )) Console.WriteLine("There is no Node in List!"); Console.WriteLine("You can press return to quit!"); try { // 確保用戶看清法式運轉成果 Console.Read( ); } catch (IOException e) { } } }