閱讀526 返回首頁    go 小米 go 小米6


C#單向鏈表的實現

using System ; public class LinkedList { //嵌套類表示單個節點; private class Node { public Node (object values) { item=values ; } public object item; //數據域; public LinkedList.Node next;//指針域; public override string ToString() { return item.ToString (); } } private int count;//記錄元素個數; public int Count { get {return this.count ;} } private Node head;//頭指針; public object this[int index]//索引器; { get {return GetByIndex (index).item;} set{GetByIndex (index).item=value ;} } //①添加元素; public void Add(object values) { Node newNode=new Node (values); if(head ==null ) //如果頭指針為空; { head =newNode ; } else { GetByIndex(count-1).next=newNode; //插到鏈表結尾; } count ++; //鏈表長度+1; } //②在指定索引處插入元素; public void Insert(int index,object values) { Node tempNode; if(index ==0) { if(head ==null ) { tempNode =new Node (values ); tempNode.next =head ; head =tempNode ; } } else { Node preNode=GetByIndex(index-1); //找插入節點的前驅; Node nextNode=preNode.next ; //找插入節點的後繼結點; tempNode =new Node (values); preNode.next =tempNode; tempNode.next =nextNode ; } count ++; } //③刪除指定索引元素; public void RemoveAt(int index) { if (index ==0) //刪除節點為頭指針; { head =head.next ; } else { Node preNode=GetByIndex(index-1); if(preNode.next ==null) { throw new ArgumentOutOfRangeException("index","索引超出範圍!"); } preNode.next =preNode.next.next ; } count --; } public override string ToString() { string s=""; for(Node temp=head; temp!=null; temp=temp.next) { s+=temp.ToString ()+" "; } return s; } private Node GetByIndex(int index) { if((index <0)||(index >= this.count )) { throw new ArgumentOutOfRangeException("index","索引超出範圍!"); } Node tempNode=this.head ; for(int i=0;i<index ;i++) { tempNode=tempNode.next ; } return tempNode ; } } class App { static void Main() { LinkedList lst=new LinkedList (); Console .WriteLine("①添加元素:"); lst .Add (0); lst .Add (1); lst .Add (2); lst .Add (3); Console .WriteLine(lst.ToString()); Console .WriteLine("②在2號位置,添加元素50:"); lst .Insert (2,50); Console .WriteLine(lst.ToString()); Console .WriteLine("③移除1號元素:"); lst.RemoveAt(1); Console .WriteLine(lst.ToString()); Console .WriteLine("④把2號元素賦值為9:"); lst [2]=9; Console .WriteLine(lst.ToString()); } }

最後更新:2017-04-02 04:00:25

  上一篇:go IBM WebSphere Application Server V6.1 Fix Pack 27於2009.09.21發布
  下一篇:go 中國密碼算法標準什麼時候才能有?