在 C# 中,单链表可以通过定义一个节点类来实现。节点类包括一个数据成员和一个指向下一个节点的指针。下面是一个示例:
public class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
next = null;
}
}
在这个示例中,节点类包含一个整数数据成员和一个指向下一个节点的指针。构造函数将节点的数据设置为传入的值,并将指针初始化为空。
使用节点类可以构建单链表。下面是一个示例:
public class LinkedList
{
public Node head;
public LinkedList()
{
head = null;
}
public void InsertAtBeginning(int data)
{
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
public void InsertAtEnd(int data)
{
Node newNode = new Node(data);
if (head == null)
{
head = newNode;
return;
}
Node current = head;
while (current.next != null)
{
current = current.next;
}
current.next = newNode;
}
public void PrintList()
{
Node current = head;
while (current != null)
{
Console.Write(current.data + " ");
current = current.next;
}
Console.WriteLine();
}
}
在这个示例中,LinkedList 类包含一个头节点和三个方法:InsertAtBeginning,InsertAtEnd 和 PrintList。
InsertAtBeginning 方法将一个新节点插入到链表的开头。它创建一个新节点,将它的 next 指针设置为头节点,然后将头节点指向新节点。
InsertAtEnd 方法将一个新节点插入到链表的末尾。如果链表为空,它将头节点设置为新节点。否则,它遍历链表,找到最后一个节点,然后将它的 next 指针设置为新节点。
PrintList 方法遍历链表并打印每个节点的数据。