Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีลบค่าที่พบครั้งแรกใน LinkedList ใน C#

บทความนี้สาธิตวิธีการลบค่า (value) ที่พบครั้งแรกใน LinkedList<T> โดยใช้ method Remove(T value)

ตัวอย่างที่ 1: ลบค่า "A" ที่พบครั้งแรก

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        LinkedList<string> list = new LinkedList<string>();
        list.AddLast("A");
        list.AddLast("B");
        list.AddLast("C");
        list.AddLast("A");
        list.AddLast("E");
        list.AddLast("F");
        list.AddLast("A");
        list.AddLast("H");
        list.AddLast("A");
        list.AddLast("J");

        Console.WriteLine("Count of nodes = " + list.Count);
        Console.WriteLine("Elements in LinkedList...");
        foreach (string res in list)
        {
            Console.WriteLine(res);
        }

        list.Remove("A");

        Console.WriteLine("Count of nodes = " + list.Count);
        Console.WriteLine("Elements in LinkedList... (After Remove)");
        foreach (string res in list)
        {
            Console.WriteLine(res);
        }
    }
}

ผลลัพธ์

Count of nodes = 10
Elements in LinkedList...
A
B
C
A
E
F
A
H
A
J
Count of nodes = 9
Elements in LinkedList... (After Remove)
B
C
A
E
F
A
H
A
J

ตัวอย่างที่ 2: ลบค่า "Three" ที่ซ้ำกัน

using System;
using System.Collections.Generic;

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

        Console.WriteLine("Count of nodes = " + list.Count);
        Console.WriteLine("Elements in LinkedList...");
        foreach (string res in list)
        {
            Console.WriteLine(res);
        }

        list.Remove("Three");

        Console.WriteLine("Count of nodes = " + list.Count);
        Console.WriteLine("Elements in LinkedList... (After Remove)");
        foreach (string res in list)
        {
            Console.WriteLine(res);
        }
    }
}

ผลลัพธ์

Count of nodes = 6
Elements in LinkedList...
One
Two
Three
Three
Three
Four
Count of nodes = 5
Elements in LinkedList... (After Remove)
One
Two
Three
Three
Four

คำอธิบายเพิ่มเติม

  • Remove(T value) ลบโหนดแรกที่มีค่าตรงกับที่ระบุ คืนค่า true ถ้าลบสำเร็จ, false ถ้าไม่พบค่า
  • ลบเฉพาะครั้งแรกที่พบ (first occurrence) เท่านั้น
  • เวลา complexity: O(n) - ต้องเดินหาค่าที่ตรงกัน
  • ถ้าต้องการลบทุกค่าที่ตรงกัน ต้องใช้ลูป while: while(list.Remove("value")) { }
  • มี method อื่นๆ: RemoveFirst(), RemoveLast(), Remove(LinkedListNode)