ใน C# คลาส LinkedList<T> มีเมธอด AddLast() สำหรับเพิ่มโหนดใหม่หรือค่าใหม่ที่ท้ายของลิงก์ลิสต์ นี่คือวิธีมาตรฐานในการสร้างลิงก์ลิสต์โดยเพิ่มข้อมูลทีละรายการ
ตัวอย่างโค้ด: เพิ่มสตริง
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
LinkedList list = new LinkedList();
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 list = new LinkedList();
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
เมธอดที่เกี่ยวข้องอื่นๆ
AddFirst(value)- เพิ่มที่หน้าลิสต์AddAfter(node, value)- เพิ่มหลังโหนดที่ระบุAddBefore(node, value)- เพิ่มก่อนโหนดที่ระบุRemoveLast()- ลบโหนดท้ายRemoveFirst()- ลบโหนดแรก
ข้อดีของ LinkedList
- การเพิ่ม/ลบที่หัว/ท้าย ใช้เวลา O(1)
- ไม่ต้องย้ายข้อมูลอื่นๆ เมื่อเพิ่ม/ลบ (ต่างจาก List/Array)
- เหมาะสำหรับการ insert/delete บ่อยๆ ที่ตำแหน่งต่างๆ
- รองรับการวนลูปด้วย
foreachและ Enumerator