您当前的位置: 首页 >  c#

光怪陆离的节日

暂无认证

  • 3浏览

    0关注

    1003博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C#实现单链表的定义、插入、删除、查找

光怪陆离的节日 发布时间:2022-06-27 16:41:06 ,浏览量:3

本文介绍C#实现单链表数据结构的定义、插入、删除、查找 1、单链表的定义 /// /// 节点类 /// /// public class ListNode { //节点值 public int Value; //前一个节点 public ListNode Previous; //后一个节点 public ListNode Next; } 2、单链表头插入法 /// /// 单链表插入–头插入法 /// /// /// public static ListNode CreatList1(ref ListNode L,int e) { //每次均在头节点之后插入元素 ListNode s = new ListNode(); s.Value = e; s.Next = null; if (L == null) { L = s; L.Next = null; } else { s.Next = L.Next; L.Next = s; } return L; } 3、单链表的尾插入法 /// /// 单链表插入—尾插法 /// /// public static ListNode CreatList2(ref ListNode L, ref ListNode real,int e) { ListNode s = new ListNode(); s.Value = e; s.Next = null; if (L == null) { L = s; real = s; real.Next = null; }else { real.Next = s; real = s; } return L; } 4、单链表的按序号查找节点值 /// /// 按序号查找节点值 /// /// /// public static ListNode GetElem(ListNode L,int i) { int j = 1; ListNode p = L.Next; if (i == 0) return L; if (i < 1) return null; while (p != null && j < i) { p = p.Next; j++; } return p; } 5、单链表按值查找节点 /// /// 按值查找节点 /// /// public static ListNode GetElem2(ListNode L, int e) { ListNode p = L; while (p!=null&&p.Value!=e) { p = p.Next; } return p; } 6、实际测试的Main函数 static void Main(string[] args) { //测试链表的构造 ListNode L = null; ListNode real = null; int i=0; int x=0; while (x!=999) { Console.WriteLine(“请输入一个数字(999结束):”); x = int.Parse(Console.ReadLine());//字符转为整型

            if (x!=999) {
                CreatList2(ref L,ref real, x);
            } 
        }
        //按序号查找结点值
        while (i != 999) {
        Console.WriteLine("请输入序号查找节点:");
        i = int.Parse(Console.ReadLine());//字符转为整型
            Console.WriteLine("序号i的值:"+ GetElem(L, i).Value);    
        }
        Console.ReadLine();
    }
}
关注
打赏
1665731445
查看更多评论
立即登录/注册

微信扫码登录

0.0437s