在 C# 中向 LinkedList 的末尾新增新節點或值


要在 LinkedList 的末尾新增新節點或值,程式碼如下 -

示例

 即時演示

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      LinkedList<String> list = new LinkedList<String>();
      list.AddLast("A");
      list.AddLast("B");
      list.AddLast("C");
      list.AddLast("D");
      list.AddLast("E");
      list.AddLast("F");
      Console.WriteLine("Count of nodes = " + list.Count);
      Console.WriteLine("Elements in LinkedList...");
      foreach (string res in list) {
         Console.WriteLine(res);
      }
      list.AddLast("G");
      list.AddLast("H");
      list.AddLast("I");
      Console.WriteLine("Count of nodes = " + list.Count);
      Console.WriteLine("Elements in LinkedList...");
      foreach (string res in list) {
         Console.WriteLine(res);
      }
   }
}

輸出

將生成以下輸出 -

Count of nodes = 6
Elements in LinkedList...
A
B
C
D
E
F
Count of nodes = 9
Elements in LinkedList...
A
B
C
D
E
F
G
H
I

示例

讓我們看另一個示例 -

 即時演示

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      LinkedList<int> list = new LinkedList<int>();
      list.AddLast(100);
      list.AddLast(200);
      list.AddLast(300);
      Console.WriteLine("Count of nodes = " + list.Count);
      Console.WriteLine("Elements in LinkedList...");
      foreach (int res in list) {
         Console.WriteLine(res);
      }
      list.AddLast(400);
      list.AddLast(500);
      list.AddLast(600);
      Console.WriteLine("Count of nodes = " + list.Count);
      Console.WriteLine("Elements in LinkedList...");
      foreach (int res in list) {
         Console.WriteLine(res);
      }
   }
}

輸出

將生成以下輸出 -

Count of nodes = 3
Elements in LinkedList...
100
200
300
Count of nodes = 6
Elements in LinkedList...
100
200
300
400
500
600

更新於: 2019 年 12 月 6 日

117 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告
© . All rights reserved.