บทความนี้สาธิตวิธีตรวจสอบว่า LinkedList<T> มีค่า (value) ที่ระบุอยู่หรือไม่ โดยใช้เมธอด Contains() ใน C#
ตัวอย่างที่ 1: ตรวจสอบค่าใน LinkedList ของจำนวนเต็ม (พบ)
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
LinkedList<int> linkedList = new LinkedList<int>();
linkedList.AddLast(25);
linkedList.AddLast(50);
linkedList.AddLast(100);
linkedList.AddLast(200);
linkedList.AddLast(400);
linkedList.AddLast(500);
linkedList.AddLast(550);
linkedList.AddLast(600);
linkedList.AddLast(800);
linkedList.AddLast(1200);
Console.WriteLine("Count of nodes = " + linkedList.Count);
foreach (int val in linkedList)
{
Console.WriteLine(val);
}
Console.WriteLine("Does the LinkedList has node 800? " + linkedList.Contains(800));
}
}
ผลลัพธ์
Count of nodes = 10 25 50 100 200 400 500 550 600 800 1200 Does the LinkedList has node 800? = True
ตัวอย่างที่ 2: ตรวจสอบค่าใน LinkedList ของสตริง (ไม่พบ)
using System;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
LinkedList<string> linkedList = new LinkedList<string>();
linkedList.AddLast("ABC");
linkedList.AddLast("BCD");
linkedList.AddLast("CDE");
linkedList.AddLast("DEF");
linkedList.AddLast("EFG");
linkedList.AddLast("FGH");
linkedList.AddLast("GHI");
linkedList.AddLast("HIJ");
linkedList.AddLast("IJK");
Console.WriteLine("Count of nodes = " + linkedList.Count);
foreach (string val in linkedList)
{
Console.WriteLine(val);
}
Console.WriteLine("Does the LinkedList has node KLM? " + linkedList.Contains("KLM"));
}
}
ผลลัพธ์
Count of nodes = 9 ABC BCD CDE DEF EFG FGH GHI HIJ IJK Does the LinkedList has node KLM? = False
สรุป
- ใช้
Contains(T value)เพื่อตรวจสอบว่ามีค่าอยู่ใน LinkedList หรือไม่ — คืนค่าbool LinkedList<T>เป็น doubly linked list — ใส่/ลบที่กลางได้ O(1) หากมี reference โหนด แต่ค้นหาเป็น O(n)- เมธอดเพิ่มโหนด:
AddFirst(),AddLast(),AddBefore(),AddAfter() - เมธอดลบโหนด:
Remove(),RemoveFirst(),RemoveLast(),Clear() - คุณสมบัติ
Countคืนจำนวนโหนด,FirstและLastคืนโหนดแรก/สุดท้าย - ประสิทธิภาพ: Contains() เป็น linear search O(n) — หากค้นหาบ่อย ควรพิจารณา
HashSet<T>หรือDictionary<TKey, TValue>แทน
เมื่อไหร่ควรใช้ LinkedList?
- ต้องการ insert/delete ที่กลางบ่อย และมี reference โหนดอยู่แล้ว
- ต้องการ enumerate ทั้ง forward และ backward (มี Previous/Next)
- ไม่ต้องการ random access by index
- ส่วนใหญ่กรณี
List<T>เร็วกว่าและสะดวกกว่า