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

การเข้าถึงโหนดแรกของ LinkedList ใน C# (First Property)


คุณสมบัติ LinkedList<T>.First ใน C# ใช้สำหรับเข้าถึงโหนดแรก (head node) ของ LinkedList คืนค่า LinkedListNode<T> ซึ่งมีคุณสมบัติ Value สำหรับดูค่าที่เก็บอยู่

ตัวอย่างที่ 1: LinkedList<string> — ดูโหนดแรกและล้าง

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

ตัวอย่างที่ 2: LinkedList<int> — ดูโหนดแรกและโหนดสุดท้าย

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

คุณสมบัติและเมธอดที่เกี่ยวข้อง

คุณสมบัติ/เมธอดคำอธิบาย
Firstโหนดแรก (head) — คืน LinkedListNode<T> หรือ null หากว่าง
Lastโหนดสุดท้าย (tail) — คืน LinkedListNode<T> หรือ null หากว่าง
AddFirst(value)เพิ่มโหนดที่ด้านหน้า
AddLast(value)เพิ่มโหนดที่ด้านหลัง
AddBefore(node, value)เพิ่มโหนดก่อนโหนดที่ระบุ
AddAfter(node, value)เพิ่มโหนดหลังโหนดที่ระบุ
RemoveFirst()ลบโหนดแรก
RemoveLast()ลบโหนดสุดท้าย

ข้อสังเกต

  • LinkedList เป็น Doubly Linked List — โหนดแต่ละตัวมี reference ไปทั้ง Next และ Previous
  • First และ Last เป็น O(1) — เข้าถึงได้ทันที
  • หาก List ว่าง First และ Last จะเป็น null — ต้องตรวจสอบก่อนเข้าถึง .Value
  • เหมาะสำหรับการแทรก/ลบบ่อยครั้งที่กลางรายการ (O(1) หากมี reference โหนด) — ต่างจาก List ที่ O(n)