单链表建表和测试
using System; using System.Collections.Generic; using System.Text; namespace link { class Program { static void Main( string [] args) { SLinkList p = new SLinkList(); // p.CreateListHead(); //头插法 p.CreateListTail(); //尾插法 p.PrintList(); //输出全部结点 Console.WriteLine( "Length={0}" ,p.GetLength()); //输出单链表长度 } } //********************************************// //链表类 class SLinkList { private SNode start; //单链表的头引用 int length=0; //单链表的长度 //初始化线性表 public SLinkList() { start = null ; } //头插法创建单链表 //public void CreateListHead( ) //{ // int d; // d = Int32.Parse(Console.ReadLine()); // while (d != -1) // { // SNode p = new SNode(d); // p.Next = start; // start = p; // d = Int32.Parse(Console.ReadLine()); // } //} //尾插法创建单链表 public void CreateListTail() { SNode R = new SNode(); int d; d = Int32.Parse(Console.ReadLine()); while (d != -1) { SNode p = new SNode(d, null ); if (start == null ) start = p; else R.Next = p; R = p; d = Int32.Parse(Console.ReadLine()); } } //输出单链表元素 public void PrintList( ) { SNode node = start; while (node != null ) { Console.WriteLine( "{0}" , node.Data); node = node.Next; } } //求单链表的长度 public int GetLength() { SNode q = start; while (q != null ) { length++; q = q.Next; } return length; } } //*****************************************************// //结点类 class SNode { private int data; //数据域 private SNode next; //引用域 public SNode( int val, SNode p) { data = val; next = p; } public SNode(SNode p) { next = p; } public SNode( int val) { data = val; next = null ; } public SNode() { data = default ( int ); next = null ; } //数据域属性 public int Data { get { return data; } set { data = value; } } //引用域属性 public SNode Next { get { return next; } set { next = value; } } } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步