设置一个LinkedList并添加元素。
string [] students = {"Beth","Jennifer","Amy","Vera"}; LinkedList<string> list = new LinkedList<string>(students);
首先,在末尾添加一个新节点。
var newNode = list.AddLast("Emma");
现在,使用该AddAfter()
方法在给定节点之后添加一个节点。
list.AddAfter(newNode, "Matt");
以下是完整的代码。
using System; using System.Collections.Generic; class Demo { static void Main() { string [] students = {"Beth","Jennifer","Amy","Vera"}; LinkedList<string> list = new LinkedList<string>(students); foreach (var stu in list) { Console.WriteLine(stu); } //在最后添加一个节点 var newNode = list.AddLast("Emma"); //在上面添加的节点之后添加一个新节点 list.AddAfter(newNode, "Matt"); Console.WriteLine("LinkedList after adding new nodes..."); foreach (var stu in list) { Console.WriteLine(stu); } } }
输出结果
Beth Jennifer Amy Vera LinkedList after adding new nodes... Beth Jennifer Amy Vera Emma Matt