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
上一篇:
IBM WebSphere Application Server V6.1 Fix Pack 27於2009.09.21發布
下一篇:
中國密碼算法標準什麼時候才能有?
小米華為智能手機未來路不平坦
遊戲安全資訊精選 2017年 第八期:從“馬甲”到“刷金”,盤點網絡遊戲的攻擊和欺詐,微軟“9月周二補丁日”發布81個漏洞補丁,係統優化工具CCleaner被植入後門
阿裏雲視頻技術專家柿蒂:視頻AI in傳媒九大業務場景解析
iOS開發學習之路 No.10 :UIColor,CGColor,CIColor三者的區別和聯係
線程同步之Semaphore
遭JBoss漏洞破壞23000台服務器“中招
5.22成都workshop:1、海量數據存儲與多媒體處理
Word中空格顯示點符號的問題
surfaceview詳解
【打表出來】poj 2363 Blocks