LinkedList<T> มี property Last คืนโหนดสุดท้าย (LinkedListNode<T>) และ First คืนโหนดแรก ใช้ .Value เพื่อเข้าถึงค่าจริง
ตัวอย่างโค้ดที่ 1: สตริง
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");
list.AddLast("G");
list.AddLast("H");
list.AddLast("I");
list.AddLast("J");
Console.WriteLine("Count of nodes = " + list.Count);
Console.WriteLine("First Node = " + list.First.Value);
Console.WriteLine("Last Node = " + list.Last.Value);
list.Clear();
Console.WriteLine("Count of nodes (updated) = " + list.Count);
}
}
ผลลัพธ์
Count of nodes = 10
First Node = A
Last Node = J
Count of nodes (updated) = 0
ตัวอย่างโค้ดที่ 2: จำนวนเต็ม
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);
list.AddLast(400);
list.AddLast(500);
list.AddLast(600);
list.AddLast(700);
list.AddLast(800);
list.AddLast(900);
list.AddLast(1000);
Console.WriteLine("Count of nodes = " + list.Count);
Console.WriteLine("First Node = " + list.First.Value);
Console.WriteLine("Last Node = " + list.Last.Value);
list.Clear();
Console.WriteLine("Count of nodes (updated) = " + list.Count);
}
}
ผลลัพธ์
Count of nodes = 10
First Node = 100
Last Node = 1000
Count of nodes (updated) = 0
LinkedListNode<T> - โหนดของ LinkedList
| Property | คำอธิบาย |
Value | ค่าที่เก็บในโหนด (T) |
Next | โหนดถัดไป (null หากเป็นท้าย) |
| Previous | โหนดก่อนหน้า (null หากเป็นหัว) |
List | LinkedList<T> ที่โหนดนี้อยู่ |
การใช้งาน Node โดยตรง
var list = new LinkedList();
list.AddLast(1);
list.AddLast(2);
list.AddLast(3);
// เพิ่มก่อนโหนดสุดท้าย
list.AddBefore(list.Last, 99); // 1, 2, 99, 3
// เพิ่มหลังโหนดแรก
list.AddAfter(list.First, 88); // 1, 88, 2, 99, 3
// ลบโหนดสุดท้าย
list.Remove(list.Last);
// เดินจากท้ายมาหัว
var node = list.Last;
while (node != null)
{
Console.WriteLine(node.Value);
node = node.Previous;
}
First/Last เมื่อว่าง
list.First และ list.Last คืน null หาก Count == 0
- ต้องเช็ค
if (list.Count > 0) ก่อนเข้าถึง .Value
LinkedList vs List<T> - สรุป
| Operation | LinkedList<T> | List<T> |
| First/Last access | O(1) via First/Last | O(1) via [0]/[^1] |
| AddFirst/AddLast | O(1) | O(1) amortized (Last), O(n) (First) |
| Insert middle (with node ref) | O(1) | O(n) |
| Remove (with node ref) | O(1) | O(n) |
| Index access | O(n) | O(1) |
| Memory overhead | High (node objects) | Low (array) |
| Cache locality | Poor | Excellent |
แนวทาง: ใช้ List<T> เป็นค่าเริ่มต้น, LinkedList<T> กรณีพิเศษ