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

วิธีลบโหนดแรกของ LinkedList ใน C#

บทความนี้สาธิตวิธีการลบโหนด (node) ตัวแรกของ LinkedList<T> ใน C# โดยใช้ method RemoveFirst()

ตัวอย่างที่ 1: ลบโหนดแรกครั้งเดียว

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.RemoveFirst();

        Console.WriteLine("Count of nodes (UPDATED) = " + list.Count);
        Console.WriteLine("Elements in LinkedList... (UPDATED)");

        foreach (string res in list)
        {
            Console.WriteLine(res);
        }
    }
}

ผลลัพธ์

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

ตัวอย่างที่ 2: ลบโหนดแรกหลายครั้งติดต่อกัน

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.RemoveFirst();
        Console.WriteLine("Count of nodes (UPDATED) = " + list.Count);
        Console.WriteLine("Elements in LinkedList... (UPDATED)");
        foreach (string res in list)
        {
            Console.WriteLine(res);
        }

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

ผลลัพธ์

Count of nodes = 6
Elements in LinkedList...
One
Two
Three
Three
Three
Four
Count of nodes (UPDATED) = 5
Elements in LinkedList... (UPDATED)
Two
Three
Three
Three
Four
Count of nodes (UPDATED AGAIN) = 4
Elements in LinkedList... (UPDATED AGAIN)
Three
Three
Three
Four

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

  • RemoveFirst() ลบโหนดแรก (head) ของ LinkedList และคืนค่า void
  • ถ้า LinkedList ว่าง จะโยน InvalidOperationException
  • เวลา complexity: O(1) - เร็วมากเพราะเพียงเปลี่ยน pointer ของ head
  • มี method คู่คือ RemoveLast() สำหรับลบโหนดท้าย
  • ใช้ foreach วนลูป LinkedList ได้โดยตรง (แทน Enumerator แบบเก่า)