Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Duyệt Singly LinkedList trong C#

C# cung cấp LinkedList<T> (namespace System.Collections.Generic) - triển khai danh sách liên kết đôi (doubly linked list). Duyệt qua nó rất đơn giản với foreach.

Ví dụ minh họa

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        var list = new LinkedList();
        
        // Thêm phần tử
        list.AddLast("Tim");
        list.AddLast("Tom");
        list.AddFirst("Ann");  // Thêm vào đầu
        
        Console.WriteLine("Duyệt theo thứ tự:");
        foreach (var item in list)
        {
            Console.WriteLine(item);
        }
        
        Console.WriteLine("\nDuyệt ngược (từ cuối về đầu):");
        for (var node = list.Last; node != null; node = node.Previous)
        {
            Console.WriteLine(node.Value);
        }
        
        Console.WriteLine($"\nSố phần tử: {list.Count}");
        Console.WriteLine($"Phần tử đầu: {list.First.Value}");
        Console.WriteLine($"Phần tử cuối: {list.Last.Value}");
    }
}

Kết quả đầu ra

Duyệt theo thứ tự:
Ann
Tim
Tom

Duyệt ngược (từ cuối về đầu):
Tom
Tim
Ann

Số phần tử: 3
Phần tử đầu: Ann
Phần tử cuối: Tom

Lưu ý: LinkedList<T> trong C# là doubly linked list (có cả Next và Previous). Nếu cần singly linked list thuần túy, tự triển khai class Node.