前言
静态链表需要一直进行循环遍历因为这时数组的顺序存储已经被改变
1.创建节点
使用struct创建数据域Value和指针域NextIndex及构造函数用来赋值。
namespace Testmain
{
public struct ListNode
{
public string Value;
public int NextIndex;
public ListNode(string value, int nextIndex)
{
Value = value;
NextIndex = nextIndex;
}
}
}
2.使用StaticLinkedList类创建链表,包含添加、展示、删除、插入
namespace Testmain
{
public class StaticLinkedList
{
//头结点,数组最大容量,静态链表
private int headIndex;
private int capacity;
private ListNode[] nodes;
//构造函数,对链表进行初始化
public StaticLinkedList(int capacity)
{
headIndex = -1;
this.capacity = capacity;
nodes = new ListNode[capacity];
}
public void addNode(string value)
{
//若链表为空直接给数组第一个个元素赋值
if (headIndex == -1)
{
headIndex = 0;
nodes[headIndex] = new ListNode(value, -1);
}
else
{
int currentIndex = headIndex;
while (nodes[currentIndex].NextIndex != -1)
{
currentIndex = nodes[currentIndex].NextIndex;
}
for (int i = 0; i < capacity; i++)
{
if (nodes[i].Value == null)
{
//找到数据域空的地址将下标给上一个元素的指针,将新添加的元素指针给-1做末尾标识。
nodes[currentIndex].NextIndex = i;
nodes[i] = new ListNode(value, -1);
break;
}
}
}
}
public void insertNode(string value, int index)
{
for (int i = 0; i < capacity; i++)
{
if (nodes[i].Value == null)
{
//找个空的地址(并不与前一个元素地址上连续)将值赋上,将要插入的下表元素的指针给插入的元素,将新元素的下表i给要插入的元素的指针。
nodes[i].Value = value;
nodes[i].NextIndex = nodes[index].NextIndex;
nodes[index].NextIndex = i;
break;
}
}
}
public void deleteNode(int index)
{
if (index < 0 || index >= capacity)
{
Console.WriteLine("Invalid index");
return;
}
if (index == headIndex)
{
//这里headIndex重新赋值为-1是为了将链表置空
headIndex = nodes[headIndex].NextIndex;
nodes[index] = new ListNode(null, -1);
}
else
{
int currentIndex = headIndex;
//当元素的指针等于要删除的下标及遍历结束中止循环
while (nodes[currentIndex].NextIndex != index && nodes[currentIndex].NextIndex != -1)
{
currentIndex = nodes[currentIndex].NextIndex;
}
if (nodes[currentIndex].NextIndex == index)
{
nodes[currentIndex].NextIndex = nodes[index].NextIndex;
nodes[index] = new ListNode(null, -1);
}
else
{
Console.WriteLine("Index not found");
}
}
}
public void PrintList()
{
int currentIndex = headIndex;
while (currentIndex != -1)
{
Console.Write(nodes[currentIndex].Value + nodes[currentIndex].NextIndex + " -> ");
currentIndex = nodes[currentIndex].NextIndex;
}
Console.WriteLine("null");
}
}
}
3、程序入口
using System;
namespace Testmain
{
class Program
{
static void Main(string[] args)
{
StaticLinkedList list = new StaticLinkedList(5);
list.addNode("A");
list.addNode("B");
list.addNode("C");
list.insertNode("D", 1);
// list.deleteNode(2);
list.PrintList();
}
}
}
本文详细介绍了如何在C#中使用Struct创建ListNode结构体以及StaticLinkedList类来实现静态链表,包括添加、展示、删除和插入节点的方法,以及程序入口展示了链表操作的使用实例。

被折叠的 条评论
为什么被折叠?



