C# 中的 LinkedList 移除方法


利用 Remove() 方法可移除 LinkedList 中節點的首次出現。

首先,讓我們使用整型元素設定一個 LinkedList。

int [] num = {2, 5, 7, 15};
LinkedList<int> list = new LinkedList<int>(num);

現在,假設你需要移除元素 7 的節點。為此,請使用 Remove() 方法。

list.Remove(7);

讓我們看看完整的程式碼。

示例

 線上演示

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      int [] num = {2, 5, 7, 15};
      LinkedList<int> list = new LinkedList<int>(num);
      foreach (var n in list) {
         Console.WriteLine(n);
      }
      // adding a node at the end
      var newNode = list.AddLast(25);
      Console.WriteLine("LinkedList after adding new nodes...");
      foreach (var n in list) {
         Console.WriteLine(n);
      }
      // removing
      list.Remove(7);
      Console.WriteLine("LinkedList after removing a node...");
      foreach (var n in list) {
         Console.WriteLine(n);
      }
   }
}

輸出

2
5
7
15
LinkedList after adding new nodes...
2
5
7
15
25
LinkedList after removing a node...
2
5
15
25

更新時間: 2020 年 6 月 23 日

1K+ 瀏覽量

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告