如何使用 C# 在單鏈表中實現遍歷?


設定帶連結的集合 -

var list = new LinkedList<string>();

現在,新增元素 -

list.AddLast("One");
list.AddLast("Two");
list.AddLast("Four");

現在,讓我們在已建立的 LinkedList 中新增新元素 -

LinkedListNode<String> node = list.Find("Four");
list.AddBefore(node, "Three");
list.AddAfter(node, "Five");

現在,讓我們看看如何在單鏈表中遍歷節點 -

示例

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(string[] args) {
      var list = new LinkedList < string > ();
      list.AddLast("One");
      list.AddLast("Two");
      list.AddLast("Four");

      Console.WriteLine("Travering...");
      foreach(var res in list) {
         Console.WriteLine(res);
      }

      LinkedListNode < String > node = list.Find("Four");
      list.AddBefore(node, "Three");
      list.AddAfter(node, "Five");

      Console.WriteLine("Travering after adding new elements...");

      foreach(var res in list) {
         Console.WriteLine(res);
      }
   }
}

更新於:2020 年 6 月 22 日

467 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

馬上開始
廣告
© . All rights reserved.