C# 程序如何向链表中指定节点前添加一个节点
声明一个 LinkedList,并为其添加节点。
string [] students = {"Tim","Jack","Henry","David","Tom"}; LinkedList<string> list = new LinkedList<string>(students);
我们添加一个新节点。
var newNode = list.AddLast("Kevin");
现在,要添加一个节点在指定节点前,使用 AddBefore() 方法。
list.AddBefore(newNode, "Matt");
现在我们来看看完整代码。
范例
using System; using System.Collections.Generic; class Demo { static void Main() { string [] students = {"Tim","Jack","Henry","David","Tom"}; LinkedList<string> list = new LinkedList<string>(students); foreach (var stu in list) { Console.WriteLine(stu); } // adding a node at the end var newNode = list.AddLast("Kevin"); // adding a new node before the node added above list.AddBefore(newNode, "Matt"); Console.WriteLine("LinkedList after adding new nodes..."); foreach (var stu in list) { Console.WriteLine(stu); } } }
输出
Tim Jack Henry David Tom LinkedList after adding new nodes... Tim Jack Henry David Tom Matt Kevin
广告