C# 中的 LinkedList AddBefore 方法
使用 AddBefore() 方法在 C# 中在给定节点之前添加节点。
我们带有字符串节点的 LinkedList。
string [] students = {"Henry","David","Tom"}; LinkedList<string> list = new LinkedList<string>(students);
现在,我们在末尾添加节点。
// adding a node at the end var newNode = list.AddLast("Brad");
使用 AddBefore() 方法在上述添加的节点之前添加节点。
list.AddBefore(newNode, "Emma");
示例
using System; using System.Collections.Generic; class Demo { static void Main() { string [] students = {"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("Brad"); // adding a new node before the node added above list.AddBefore(newNode, "Emma"); Console.WriteLine("LinkedList after adding new nodes..."); foreach (var stu in list) { Console.WriteLine(stu); } } }
输出
Henry David Tom LinkedList after adding new nodes... Henry David Tom Emma Brad
广告