温馨提示×

c#单链表如何进行遍历操作

c#
小樊
81
2024-10-18 11:32:22
栏目: 编程语言

在C#中,遍历单链表通常使用for循环或foreach循环。首先,需要创建一个表示链表节点的类,如下所示:

public class ListNode
{
    public int Value { get; set; }
    public ListNode Next { get; set; }
}

接下来,创建一个链表并添加一些节点:

ListNode head = new ListNode { Value = 1 };
head.Next = new ListNode { Value = 2 };
head.Next.Next = new ListNode { Value = 3 };
head.Next.Next.Next = new ListNode { Value = 4 };

使用for循环遍历链表:

for (int i = 0; i < head.Next.Count; i++)
{
    ListNode currentNode = head.Next;
    Console.WriteLine(currentNode.Value);
    currentNode = currentNode.Next;
}

使用foreach循环遍历链表:

ListNode currentNode = head.Next;
foreach (int value in currentNode)
{
    Console.WriteLine(value);
}

请注意,这里的head.Next.Countforeach (int value in currentNode)仅适用于特定类型的链表(例如,当链表节点包含一个整数时)。对于更通用的单链表实现,您需要使用其他方法来遍历链表,例如使用一个索引变量。

0