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

本文介绍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();
    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光怪陆离的节日

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值