在連結串列中給定節點後新增節點的 C# 程式
設定一個 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); } // adding a node at the end var newNode = list.AddLast("Emma"); // adding a new node after the node added above 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
廣告