如何使用 C# 在单链表中实现遍历?
设置带链接的集合 -
var list = new LinkedList<string>();
现在,添加元素 -
list.AddLast("One"); list.AddLast("Two"); list.AddLast("Four");
现在,让我们在已创建的 LinkedList 中添加新元素 -
LinkedListNode<String> node = list.Find("Four"); list.AddBefore(node, "Three"); list.AddAfter(node, "Five");
现在,让我们看看如何在单链表中遍历节点 -
示例
using System; using System.Collections.Generic; public class Demo { public static void Main(string[] args) { var list = new LinkedList < string > (); list.AddLast("One"); list.AddLast("Two"); list.AddLast("Four"); Console.WriteLine("Travering..."); foreach(var res in list) { Console.WriteLine(res); } LinkedListNode < String > node = list.Find("Four"); list.AddBefore(node, "Three"); list.AddAfter(node, "Five"); Console.WriteLine("Travering after adding new elements..."); foreach(var res in list) { Console.WriteLine(res); } } }
广告