標籤:style class blog code http ext
相對於數組來說:
優點: 通過索引(數組下標)快地訪問數組元素;
缺點: 插入/刪除元素需要對數組進行調整, 效率低;
而鏈表:
優點:插入/刪除速度快而且用對整鏈表進行調整;
缺點:只能進行順序訪問能隨機訪問(像數組樣用下標);
所鏈表些需要快速插入/刪除而太關心或者需要隨機訪問情況下使用.
using System;namespace ConsoleApplication3{ class CirculLinkedList { //元素個數 private int count; //尾指標 private Node tail; //當前節點的前節點 private Node CurrPrev; //增加元素 public void Add(object value) { Node newNode = new Node(value); if (tail==null) {//鏈表為空白 tail = newNode; tail.next = newNode; CurrPrev = newNode; } else {//鏈表不為空白,把元素增加到鏈表結尾 newNode.next = tail.next; tail.next = newNode; if (CurrPrev==tail) { CurrPrev = newNode; } tail = newNode; } count++; } //刪除當前元素 public void RemoveCurrNode() { //為null代表為空白表 if (tail == null) { throw new NullReferenceException("集合中沒有任何元素!"); } else if (count==1) { tail = null; CurrPrev = null; } else { if (CurrPrev.next==tail) { tail = CurrPrev; } CurrPrev.next = CurrPrev.next.next; } count--; } //當前節點移動步數 public void Move(int step) { if (step<0) { throw new ArgumentOutOfRangeException("step", "移動步數不可為負數!"); } if (tail==null) { throw new NullReferenceException("鏈表為空白!"); } for (int i = 0; i < step; i++) { CurrPrev = CurrPrev.next; } } //獲得當前節點 public object Current { get {return CurrPrev.next.item ;} } public override string ToString() { if (tail==null) { return string.Empty; } string s = ""; Node temp = tail.next; for (int i = 0; i < count; i++) { s += temp.ToString() + " "; temp = temp.next; } return s; } public int Count { get {return count ;} } private class Node { public Node(object value) { item = value; } //放置資料 public object item; public CirculLinkedList.Node next; public override string ToString() { return item.ToString(); } } }}
using System;namespace ConsoleApplication3{ class Program { static void Main(string[] args) { CirculLinkedList lst = new CirculLinkedList(); lst.Add(1); lst.Add(2); lst.Add(3); lst.Add(4); lst.Add(5); lst.Add(6); Console.WriteLine(lst.ToString()); Console.WriteLine(lst.Current.ToString()); lst.RemoveCurrNode(); Console.WriteLine(lst.ToString()); lst.Move(2); Console.WriteLine(lst.Current.ToString()); Console.WriteLine( lst.ToString()); Console.ReadLine(); } }}