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

更新時間:2020 年 6 月 23 日

197 次瀏覽

開啟您的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.