C#定义并实现单链表实例解析
2023-06-13 09:15:38 时间
本文以实例详细描述了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) { } } }
相关文章
- C#实现简单打印的实例代码
- c#多图片上传并生成缩略图的实例代码
- C#泛型与非泛型性能比较的实例
- C#将htmltable导出成excel实例
- c#获取网页中指定的字符串信息的实例代码
- C#实现写入与读出文本文件的实例代码
- C#.NET发送邮件的实例代码
- C#中通过API实现的打印类实例代码
- C#实现微信公众号群发消息(解决一天只能发一次的限制)实例分享
- C#实现大数字运算的实例代码
- c#indepth的泛型实现实例代码
- C#传值方式实现不同程序窗体间通信实例
- C#定时器定时更新的简单实例
- c#只读字段和常量的区别,以及静态构造函数的使用实例
- C#中把Datatable转换为Json的5个代码实例
- C#中DataTable排序、检索、合并等操作实例
- C#实现随鼠标移动窗体实例
- C#Page用于各页面继承功能实例
- C#基于DBContext(EF)实现通用增删改查的REST方法实例
- C#实现Log4Net日志分类和自动维护实例
- C#预处理器指令的用法实例分析
- 基于C#实现一个最简单的HTTP服务器实例
- C#入门之窗体的简单用法实例
- C#实现根据数字序号输出星期几的简单实例
- 基于C#实现的端口扫描器实例代码
- C#实现装箱与拆箱操作简单实例
- C#委托delegate实例解析
- C#生成随机数实例
- C#利用Windows自带gdi32.dll实现抓取屏幕功能实例
- C#分屏控件用法实例
- C#实现排列组合算法完整实例
- C#利用Openxml读取Excel数据实例
- C#控制台程序中处理2个关闭事件的代码实例