ตั้งค่า LinkedList
int [] num = {1, 2, 3, 4, 5};
LinkedList<int> list = new LinkedList<int>(num); ตอนนี้เพิ่มโหนดที่ส่วนท้ายโดยใช้วิธี AddLast()
var newNode = list.AddLast(20);
หากต้องการเพิ่มโหนดหลังโหนดที่เพิ่มข้างต้น ให้ใช้เมธอด AddAfter()
list.AddAfter(newNode, 30);
ตัวอย่าง
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
int [] num = {1, 2, 3, 4, 5};
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(20);
// adding a new node after the node added above
list.AddAfter(newNode, 30);
Console.WriteLine("LinkedList after adding new nodes...");
foreach (var n in list) {
Console.WriteLine(n);
}
}
} ผลลัพธ์
1 2 3 4 5 LinkedList after adding new nodes... 1 2 3 4 5 20 30