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();
}
}
相关文章
- MongoDB C# 驱动的各种版本下载地址
- 微信公众号开发C#系列-3、搭建微信本地调试环境-借助花生壳实现内网穿透
- 【转载】初学C#编程的注意事项
- 那些年困扰我们的委托(C#)
- C#实现二叉树非递归中序遍历程序
- C#程序设计接口的定义和用法
- EncryptionAndDecryptionC# 加密 解密
- C#实现文件压缩解压类
- C#图像处理-EmguCV相机标定与畸变矫正 实现代码
- ·c#之Thread实现暂停继续(转)
- C# - SPC(Statistical Process Control)系统 - 6西格玛数据决策和Chart模块的开发与实现
- C# 实现启用或停止本地网络连接
- 在C#代码中应用Log4Net(三)Log4Net中配置文件的解释
- C#进阶系列——MEF实现设计上的“松耦合”(终结篇:面向接口编程)
- 【c#】24点游戏的实现(可存档且局域网互联)
- Unity3d C# 实现UGUI面板跟随标注3D模型功能(含源码)
- Unity3d C#实现UI节点切换顺序SiblingIndex(上移、下移和快速置顶、置底)等功能(含源码)
- 为第一次接触编程的C#初学者释义
- .NET Core(C#) 使用IHttpClientFactory实现爬虫执行GET和POST请求
- C#中的匿名函数使用,类名<T>
- C#实现邮件发送的功能
- C# 已知点和向量,求距离的点
- C#中用RichTextBox实现图文混排和保存的例子