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

Xóa nút đầu tiên của LinkedList trong C#

Giới thiệu

Để xóa nút ở đầu LinkedList<T>, bạn sử dụng phương thức RemoveFirst(). Dưới đây là các ví dụ minh họa việc xóa một hoặc nhiều nút đầu tiên.

Ví dụ 1: Xóa một nút đầu tiên

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("Số lượng nút = " + list.Count);
        Console.WriteLine("Các phần tử trong LinkedList...");
        foreach (string res in list)
            Console.WriteLine(res);

        list.RemoveFirst();

        Console.WriteLine("Số lượng nút (đã cập nhật) = " + list.Count);
        Console.WriteLine("Các phần tử trong LinkedList... (đã cập nhật)");
        foreach (string res in list)
            Console.WriteLine(res);
    }
}

Kết quả

Số lượng nút = 6
Các phần tử trong LinkedList...
One
Two
Three
Three
Three
Four
Số lượng nút (đã cập nhật) = 5
Các phần tử trong LinkedList... (đã cập nhật)
Two
Three
Three
Three
Four

Ví dụ 2: Xóa nhiều nút đầu tiên liên tiếp

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("Số lượng nút = " + list.Count);
        Console.WriteLine("Các phần tử trong LinkedList...");
        foreach (string res in list)
            Console.WriteLine(res);

        list.RemoveFirst();
        Console.WriteLine("Số lượng nút (đã cập nhật) = " + list.Count);
        Console.WriteLine("Các phần tử trong LinkedList... (đã cập nhật)");
        foreach (string res in list)
            Console.WriteLine(res);

        list.RemoveFirst();
        Console.WriteLine("Số lượng nút (cập nhật lần 2) = " + list.Count);
        Console.WriteLine("Các phần tử trong LinkedList... (cập nhật lần 2)");
        foreach (string res in list)
            Console.WriteLine(res);
    }
}

Kết quả

Số lượng nút = 6
Các phần tử trong LinkedList...
One
Two
Three
Three
Three
Four
Số lượng nút (đã cập nhật) = 5
Các phần tử trong LinkedList... (đã cập nhật)
Two
Three
Three
Three
Four
Số lượng nút (cập nhật lần 2) = 4
Các phần tử trong LinkedList... (cập nhật lần 2)
Three
Three
Three
Four

Lưu ý: Nếu LinkedList rỗng, gọi RemoveFirst() sẽ ném ra ngoại lệ InvalidOperationException.