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

LinkedList trong C#

LinkedList<T> trong System.Collections.Generic - doubly linked list, insert/delete O(1) tại node đã biết.

Đặc điểm

  • Doubly linked (có Next và Previous)
  • Cho phép duplicate
  • Không index-based access (không có [i])
  • Memory overhead cao hơn List (node object)

Ví dụ

using System;
using System.Collections.Generic;

class Demo
{
    static void Main()
    {
        var list = new LinkedList<string>();
        list.AddLast("one");
        list.AddLast("two");
        list.AddLast("three");
        
        foreach (var item in list)
            Console.WriteLine(item);
    }
}

Kết quả

one
two
three

Method chính

  • AddFirst, AddLast, AddBefore(node, val), AddAfter(node, val)
  • Find(val), FindLast(val) -> trả LinkedListNode<T>
  • Remove(val), Remove(node), RemoveFirst(), RemoveLast()
  • First, Last, Count

Khi nào dùng

  • Thường insert/delete ở giữa
  • Queue/Deque implementation
  • Không cần random access
  • Ngược lại: Dùng List<T> cho hầu hết trường hợp (cache-friendly, ít overhead)