声明一个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); } //在最后添加一个节点 var newNode = list.AddLast("Kevin"); //在上面添加的节点之前添加一个新节点 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