C#定义并实现单链表实例解析
本文以实例详细描述了C#定义并实现单链表的过程及原理。一般来说C#定义并实现单链表,代码包括构成链表的结点定义、用变量来实现表头、清空整个链表、链表复位,使第一个结点成为当前结点、判断链表是否为空、判断当前结点是否为最后一个结点、返回当前结点的下一个结点的值,并使其成为当前结点、将当前结点移出链表,下一个结点成为当前结点等内容。
具体实现代码如下所示:
usingSystem; usingSystem.IO; //构成链表的结点定义 publicclassNode { publicObjectdata; publicNodenext; publicNode(Objectd) { data=d; next=null; } } publicclassList { //用变量来实现表头 privateNodeHead=null; privateNodeTail=null; privateNodePointer=null; privateintLength=0; //清空整个链表 publicvoiddeleteAll() { Head=null; Tail=null; Pointer=null; Length=0; } //链表复位,使第一个结点成为当前结点 publicvoidreset() { Pointer=null; } //判断链表是否为空 publicboolisEmpty() { return(Length==0); } //判断当前结点是否为最后一个结点 publicboolisEnd() { if(Length==0) thrownewSystem.Exception(); elseif(Length==1) returntrue; else return(cursor()==Tail); } //返回当前结点的下一个结点的值,并使其成为当前结点 publicObjectnextNode() { if(Length==1) thrownewSystem.Exception(); elseif(Length==0) thrownewSystem.Exception(); else { Nodetemp=cursor(); Pointer=temp; if(temp!=Tail) return(temp.next.data); else thrownewSystem.Exception(); } } //返回当前结点的值 publicObjectcurrentNode() { Nodetemp=cursor(); returntemp.data; } //在当前结点前插入一个结点,并使其成为当前结点 publicvoidinsert(Objectd) { Nodee=newNode(d); if(Length==0) { Tail=e; Head=e; } else { Nodetemp=cursor(); e.next=temp; if(Pointer==null) Head=e; else Pointer.next=e; } Length++; } //返回链表的大小 publicintsize() { returnLength; } //将当前结点移出链表,下一个结点成为当前结点 //如果移出的结点是最后一个结点,则第一个结点成为当前结点 publicObjectremove() { Objecttemp; if(Length==0) thrownewSystem.Exception(); elseif(Length==1) { temp=Head.data; deleteAll(); } else { Nodecur=cursor(); temp=cur.data; if(cur==Head) Head=cur.next; elseif(cur==Tail) { Pointer.next=null; Tail=Pointer; reset(); } else Pointer.next=cur.next; Length--; } returntemp; } //返回当前结点的指针 privateNodecursor() { if(Head==null) thrownewSystem.Exception(); elseif(Pointer==null) returnHead; else returnPointer.next; } //链表的简单应用举例 publicstaticvoidMain() { Lista=newList(); for(inti=1;i<=10;i++) a.insert(newIntPtr(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("ThereisnoNodeinList!"); Console.WriteLine("Youcanpressreturntoquit!"); try { //确保用户看清程序运行结果 Console.Read(); } catch(IOExceptione) { } } }