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

การได้จำนวนโหนดใน LinkedList ใน C#

ใน C# คลาส LinkedList<T> มี property Count ที่คืนค่าจำนวนโหนด (nodes) ที่อยู่ในลิสต์ปัจจุบัน นี่เป็นวิธีที่เร็วที่สุดและตรงไปตรงมาที่สุดในการทราบขนาดของลิงก์ลิสต์

ตัวอย่างโค้ด

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);
        list.Clear();
        Console.WriteLine("Count of nodes (updated) = " + list.Count);
    }
}

ผลลัพธ์

Count of nodes = 10
First Node = A
Count of nodes (updated) = 0

ตัวอย่างเพิ่มเติม: หลาย LinkedList และการเปรียบเทียบ

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main(string[] args)
    {
        LinkedList list1 = new LinkedList();
        list1.AddLast("One");
        list1.AddLast("Two");
        list1.AddLast("Three");
        list1.AddLast("Four");
        list1.AddLast("Five");

        Console.WriteLine("Elements in LinkedList1...");
        foreach (string res in list1)
        {
            Console.WriteLine(res);
        }

        LinkedList list2 = new LinkedList();
        list2.AddLast("India");
        list2.AddLast("US");
        list2.AddLast("UK");
        list2.AddLast("Canada");
        list2.AddLast("Poland");
        list2.AddLast("Netherlands");

        Console.WriteLine("Elements in LinkedList2...");
        foreach (string res in list2)
        {
            Console.WriteLine(res);
        }

        LinkedList list3 = new LinkedList();
        Console.WriteLine("Count of nodes in LinkedList3 = " + list3.Count);
        list3 = list2; // การกำหนดอ้างอิง (reference assignment)
        Console.WriteLine("Count of nodes in LinkedList3 (Updated) = " + list2.Count);
        Console.WriteLine("Is LinkedList3 equal to LinkedList2? = " + list3.Equals(list2));
    }
}

ผลลัพธ์

Elements in LinkedList1...
One
Two
Three
Four
Five
Elements in LinkedList2...
India
US
UK
Canada
Poland
Netherlands
Count of nodes in LinkedList3 = 0
Count of nodes in LinkedList3 (Updated) = 6
Is LinkedList3 equal to LinkedList2? = True

สรุป

  • ใช้ property Count เพื่อดูจำนวนโหนด - ทำงานใน O(1)
  • First และ Last ให้โหนดแรกและสุดท้ายตามลำดับ
  • Clear() ลบโหนดทั้งหมด ทำให้ Count กลายเป็น 0
  • การกำหนด list3 = list2 ทำให้ทั้งสองตัวแปรอ้างอิงไปยังอ็อบเจ็กต์เดียวกัน (reference equality)
  • Equals() สำหรับ LinkedList จะตรวจสอบ reference equality ไม่ใช่ value equality