C# 中的 LinkedList AddBefore 方法

csharpprogrammingserver side programming更新于 2025/8/10 19:37:17

在 C# 中使用 AddBefore() 方法在给定节点前添加一个节点。

我们的 LinkedList 包含字符串节点。

string [] students = {"Henry","David","Tom"};
LinkedList<string> list = new LinkedList<string>(students);

现在,让我们在末尾添加一个节点。

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

相关文章