.NET Framework 类库
LinkedList 泛型类

注意:此类在 .NET Framework 2.0 版中是新增的。

表示双向链表。

命名空间:System.Collections.Generic
程序集:System(在 system.dll 中)

语法

Visual Basic(声明)
<SerializableAttribute> _
<ComVisibleAttribute(False)> _
Public Class LinkedList(Of T)
    Implements ICollection(Of T), IEnumerable(Of T), _
    ICollection, IEnumerable, ISerializable, IDeserializationCallback
Visual Basic(用法)
Dim instance As LinkedList(Of T)
C#
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
public class LinkedList<T> : ICollection<T>, IEnumerable<T>, 
    ICollection, IEnumerable, ISerializable, IDeserializationCallback
C++
[SerializableAttribute] 
[ComVisibleAttribute(false)] 
generic<typename T>
public ref class LinkedList : ICollection<T>, IEnumerable<T>, 
    ICollection, IEnumerable, ISerializable, IDeserializationCallback
J#
J# 支持使用泛型类型和方法,但不支持进行新的声明。
JScript
JScript 支持泛型类型和方法。

类型参数

T

指定链表的元素类型。

备注

LinkedList 为通用链表。它支持枚举数并实现 ICollection 接口,与 .NET Framework 中的其他集合类一致。

LinkedList 是实际链表,包含 LinkedListNode 类型的单独节点,因此插入和移除的运算复杂度为 O(1)。如果节点及其值是同时创建的,则包含引用类型的列表性能会更好。由于基础节点是公开的,因此可以移除节点,然后在同一列表或其他列表中再重新插入它们,就像在 GC 堆中不执行分配的 O(1) 运算一样。该列表还维护内部计数,因此获取 Count 属性的运算复杂度为 O(1);如果在单个线程中使用该列表,则该计数保持一致。

LinkedList 类不支持使列表处于不一致状态的链接、拆分、循环或其他功能。设计支持维护列表的完整性,而且在单个线程上执行操作中,列表保持一致。LinkedList 支持的唯一多线程方案是多线程读取操作。在其他多线程方案中,必须提供您自己的同步。

Note注意

始终可以创建在特定环境下性能更优或牺牲编程安全性而换取其他功能的链表。

LinkedList 中的每个节点都属于 LinkedListNode 类型。由于 LinkedList 是双向链表,因此每个节点向前指向 Next 节点,向后指向 Previous 节点。节点链接至该列表,因此对该列表执行的无效操作(例如,尝试移除实际位于其他列表中的节点)不会将该列表置于不一致的状态。

LinkedList 接受 空引用(在 Visual Basic 中为 Nothing) 作为引用类型的有效 Value,并且允许重复值。

如果 LinkedList 为空,则 FirstLast 属性为 空引用(在 Visual Basic 中为 Nothing)。

示例

下面的代码示例演示 LinkedList 类的多种功能。此示例创建一个字符串数组,然后通过将该字符串数组传递给 LinkedList(泛型 IEnumerable) 构造函数,创建并填充字符串的 LinkedList

此代码示例使用 LinkedList 类的属性和方法操作生成的链接列表,同时显示操作间的结果。

Visual Basic
Imports System
Imports System.Text
Imports System.Collections.Generic

Public Class Example

    Public Shared Sub Main()

        Dim words() As String = _
            { "the", "fox", "jumped", "over", "the", "dog" }
        Dim sentence As New LinkedList(Of String)(words)
        Display(sentence)

        Console.WriteLine("sentence.Contains(""jumped"") = {0}", _
            sentence.Contains("jumped"))

        ' Add the word "today" to the beginning of the linked list.
        ' Remove the new node, and add it to the end of the list.
        sentence.AddFirst("today")
        Display(sentence)

        Dim mark1 As LinkedListNode(Of String) = sentence.First
        sentence.RemoveFirst()
        sentence.AddLast(mark1)
        Display(sentence)

        sentence.RemoveLast()
        sentence.AddLast("yesterday")
        Display(sentence)

        mark1 = sentence.Last
        sentence.RemoveLast()
        sentence.AddFirst(mark1)
        Display(sentence)

        sentence.RemoveFirst()

        Dim current As LinkedListNode(Of String) = _
            sentence.FindLast("the")
        DisplayNode(current)

        sentence.AddAfter(current, "old")
        sentence.AddAfter(current, "lazy")
        DisplayNode(current)

        current = sentence.Find("fox")
        DisplayNode(current)

        sentence.AddBefore(current, "quick")
        sentence.AddBefore(current, "brown")
        DisplayNode(current)

        ' Keep a reference to the current node, "fox", and to the
        ' previous node in the list. Use the Find method to locate
        ' the node containing the value "dog". Show the position.
        mark1 = current
        Dim mark2 As LinkedListNode(Of String) = current.Previous
        current = sentence.Find("dog")
        DisplayNode(current)

        ' The AddBefore method throws an InvalidOperationException
        ' if you try to add a node that already belongs to a list.
        Try
            sentence.AddBefore(current, mark1)
        Catch ex As InvalidOperationException
            Console.WriteLine("Exception message: {0}", ex.Message)
        End Try

        ' Remove the node referred to by mark1, and add it before 
        ' the node referred to by current. Show the sentence, 
        ' highlighting the position of the node referred to by
        ' current.
        sentence.Remove(mark1)
        sentence.AddBefore(current, mark1)
        DisplayNode(current)

        ' Remove the node referred to by current. If you try to show
        ' its position now, the DisplayNode method prints a message.
        ' Add the node after the node referred to by mark2, and 
        ' display the sentence, highlighting current.
        sentence.Remove(current)
        DisplayNode(current)
        sentence.AddAfter(mark2, current)
        DisplayNode(current)

        ' The Remove method finds and removes the first node that 
        ' that has the specified value.
        sentence.Remove("old")
        Display(sentence)

        ' When the linked list is cast to ICollection(Of String),
        ' the Add method adds a node to the end of the list. 
        sentence.RemoveLast()
        Dim icoll As ICollection(Of String) = sentence
        icoll.Add("rhinoceros")
        Display(sentence)

        ' Create an array, specifying a size one less than the size
        ' of the linked list, because Visual Basic allocates one 
        ' more element than you specify.
        Console.WriteLine(vbLf & "Copy the list to an array.")
        Dim sArray(sentence.Count - 1) As String 
        sentence.CopyTo(sArray, 0)

        For Each s As String In sArray
            Console.WriteLine(s)
        Next

        ' Release all the nodes.
        sentence.Clear()

    End Sub

    Private Shared Sub Display(ByVal words As LinkedList(Of String))
        For Each word As String In words
            Console.Write(word & " ")
        Next
        Console.WriteLine()
    End Sub
    
    Private Shared Sub DisplayNode(ByVal node As LinkedListNode(Of String))
        If node.List Is Nothing Then
            Console.WriteLine("Node ""{0}"" is not in a list.", node.Value)
            Return
        End If

        Dim result As New StringBuilder ("(" & node.Value & ")")
        Dim nodeP As LinkedListNode(Of String) = node.Previous

        While nodeP IsNot Nothing
            result.Insert(0, nodeP.Value & " ")
            nodeP = nodeP.Previous
        End While

        node = node.Next
        While node IsNot Nothing
            result.Append(" " & node.Value)
            node = node.Next
        End While

        Console.WriteLine(result)
    End Sub

End Class

'This code example produces the following output:
'
'the fox jumped over the dog
'sentence.Contains("jumped") = True
'today the fox jumped over the dog
'the fox jumped over the dog today
'the fox jumped over the dog yesterday
'yesterday the fox jumped over the dog
'the fox jumped over (the) dog
'the fox jumped over (the) lazy old dog
'the (fox) jumped over the lazy old dog
'the quick brown (fox) jumped over the lazy old dog
'the quick brown fox jumped over the lazy old (dog)
'Exception message: The LinkedList node belongs a LinkedList.
'the quick brown jumped over the lazy old fox (dog)
'Node "dog" is not in a list.
'the quick brown (dog) jumped over the lazy old fox
'the quick brown dog jumped over the lazy fox
'the quick brown dog jumped over the lazy rhinoceros
'
'Copy the list to an array.
'the
'quick
'brown
'dog
'jumped
'over
'the
'lazy
'rhinoceros
C#
using System;
using System.Text;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        string[] words = 
            {"the", "fox", "jumped", "over", "the", "dog"};
        LinkedList<string> sentence = new LinkedList<string>(words);
        Display(sentence);

        Console.WriteLine("sentence.Contains(\"jumped\") = {0}", 
            sentence.Contains("jumped"));

        // Add the word "today" to the beginning of the linked list.
        // Remove the new node, and add it to the end of the list.
        sentence.AddFirst("today");
        Display(sentence);

        LinkedListNode<string> mark1 = sentence.First;
        sentence.RemoveFirst();
        sentence.AddLast(mark1);
        Display(sentence);

        sentence.RemoveLast();
        sentence.AddLast("yesterday");
        Display(sentence);

        mark1 = sentence.Last;
        sentence.RemoveLast();
        sentence.AddFirst(mark1);
        Display(sentence);

        sentence.RemoveFirst();

        LinkedListNode<string> current = sentence.FindLast("the");
        DisplayNode(current);

        sentence.AddAfter(current, "old");
        sentence.AddAfter(current, "lazy");
        DisplayNode(current);

        current = sentence.Find("fox");
        DisplayNode(current);

        sentence.AddBefore(current, "quick");
        sentence.AddBefore(current, "brown");
        DisplayNode(current);

        // Keep a reference to the current node, "fox", and to the
        // previous node in the list. Use the Find method to locate
        // the node containing the value "dog". Show the position.
        mark1 = current;
        LinkedListNode<string> mark2 = current.Previous;
        current = sentence.Find("dog");
        DisplayNode(current);

        // The AddBefore method throws an InvalidOperationException
        // if you try to add a node that already belongs to a list.
        try
        {
            sentence.AddBefore(current, mark1);
        }
        catch(InvalidOperationException ex)
        {
            Console.WriteLine("Exception message: {0}", ex.Message);
        }

        // Remove the node referred to by mark1, and add it before 
        // the node referred to by current. Show the sentence, 
        // highlighting the position of the node referred to by
        // current.
        sentence.Remove(mark1);
        sentence.AddBefore(current, mark1);
        DisplayNode(current);

        // Remove the node referred to by current. If you try to show
        // its position now, the DisplayNode method prints a message.
        // Add the node after the node referred to by mark2, and 
        // display the sentence, highlighting current.
        sentence.Remove(current);
        DisplayNode(current);
        sentence.AddAfter(mark2, current);
        DisplayNode(current);

        // The Remove method finds and removes the first node that 
        // that has the specified value.
        sentence.Remove("old");
        Display(sentence);

        // When the linked list is cast to ICollection(Of String),
        // the Add method adds a node to the end of the list. 
        sentence.RemoveLast();
        ICollection<string> icoll = sentence;
        icoll.Add("rhinoceros");
        Display(sentence);

        // Create an array with the same number of elements as the
        // linked list.
        Console.WriteLine("\nCopy the list to an array.");
        string[] sArray = new string[sentence.Count];
        sentence.CopyTo(sArray, 0);

        foreach( string s in sArray )
        {
            Console.WriteLine(s);
        }

        // Release all the nodes.
        sentence.Clear();

    }

    private static void Display(LinkedList<string> words)
    {
        foreach( string word in words )
        {
            Console.Write(word + " ");
        }
        Console.WriteLine();
    }
    
    private static void DisplayNode(LinkedListNode<string> node)
    {
        if (node.List==null)
        {
            Console.WriteLine("Node \"{0}\" is not in a list.", 
                node.Value);
            return;
        }

        StringBuilder result = new StringBuilder("(" + node.Value + ")");
        LinkedListNode<string> nodeP = node.Previous;

        while (nodeP != null)
        {
            result.Insert(0, nodeP.Value + " ");
            nodeP = nodeP.Previous;
        }

        node = node.Next;
        while (node != null)
        {
            result.Append(" " + node.Value);
            node = node.Next;
        }

        Console.WriteLine(result);
    }
}

//This code example produces the following output:
//
//the fox jumped over the dog
//sentence.Contains("jumped") = True
//today the fox jumped over the dog
//the fox jumped over the dog today
//the fox jumped over the dog yesterday
//yesterday the fox jumped over the dog
//the fox jumped over (the) dog
//the fox jumped over (the) lazy old dog
//the (fox) jumped over the lazy old dog
//the quick brown (fox) jumped over the lazy old dog
//the quick brown fox jumped over the lazy old (dog)
//Exception message: The LinkedList node belongs a LinkedList.
//the quick brown jumped over the lazy old fox (dog)
//Node "dog" is not in a list.
//the quick brown (dog) jumped over the lazy old fox
//the quick brown dog jumped over the lazy fox
//the quick brown dog jumped over the lazy rhinoceros
//
//Copy the list to an array.
//the
//quick
//brown
//dog
//jumped
//over
//the
//lazy
//rhinoceros
C++
#using <System.dll>

using namespace System;
using namespace System::Text;
using namespace System::Collections::Generic;

void Display(LinkedList<String^>^ words)
{
    for each( String^ word in words )
    {
        Console::Write(word + " ");
    }
    Console::WriteLine();
};
    
void DisplayNode(LinkedListNode<String^>^ node)
{
    if (node->List == nullptr)
    {
        Console::WriteLine("Node \"{0}\" is not in a list.", 
            node->Value);
        return;
    }

    StringBuilder^ result = gcnew StringBuilder("(" + node->Value + ")");
    LinkedListNode<String^>^ nodeP = node->Previous;

    while (nodeP != nullptr)
    {
        result->Insert(0, nodeP->Value + " ");
        nodeP = nodeP->Previous;
    }

    node = node->Next;
    while (node != nullptr)
    {
        result->Append(" " + node->Value);
        node = node->Next;
    }

    Console::WriteLine(result);
};

void main()
{
    array<String^>^ words = 
        {"the", "fox", "jumped", "over", "the", "dog"};
    LinkedList<String^>^ sentence = 
        gcnew LinkedList<String^>((IEnumerable<String^>^) words);
    Display(sentence);

    Console::WriteLine("sentence->Contains(\"jumped\") = {0}", 
        sentence->Contains("jumped"));

    // Add the word "today" to the beginning of the linked list.
    // Remove the new node, and add it to the end of the list.
    sentence->AddFirst("today");
    Display(sentence);

    LinkedListNode<String^>^ mark1 = sentence->First;
    sentence->RemoveFirst();
    sentence->AddLast(mark1);
    Display(sentence);

    sentence->RemoveLast();
    sentence->AddLast("yesterday");
    Display(sentence);

    mark1 = sentence->Last;
    sentence->RemoveLast();
    sentence->AddFirst(mark1);
    Display(sentence);

    sentence->RemoveFirst();

    LinkedListNode<String^>^ current = sentence->FindLast("the");
    DisplayNode(current);

    sentence->AddAfter(current, "old");
    sentence->AddAfter(current, "lazy");
    DisplayNode(current);

    current = sentence->Find("fox");
    DisplayNode(current);

    sentence->AddBefore(current, "quick");
    sentence->AddBefore(current, "brown");
    DisplayNode(current);

    // Keep a reference to the current node, "fox", and to the
    // previous node in the list. Use the Find method to locate
    // the node containing the value "dog". Show the position.
    mark1 = current;
    LinkedListNode<String^>^ mark2 = current->Previous;
    current = sentence->Find("dog");
    DisplayNode(current);

    // The AddBefore method throws an InvalidOperationException
    // if you try to add a node that already belongs to a list.
    try
    {
        sentence->AddBefore(current, mark1);
    }
    catch(InvalidOperationException^ ex)
    {
        Console::WriteLine("Exception message: {0}", ex->Message);
    }

    // Remove the node referred to by mark1, and add it before 
    // the node referred to by current. Show the sentence, 
    // highlighting the position of the node referred to by
    // current.
    sentence->Remove(mark1);
    sentence->AddBefore(current, mark1);
    DisplayNode(current);

    // Remove the node referred to by current. If you try to show
    // its position now, the DisplayNode method prints a message.
    // Add the node after the node referred to by mark2, and 
    // display the sentence, highlighting current.
    sentence->Remove(current);
    DisplayNode(current);
    sentence->AddAfter(mark2, current);
    DisplayNode(current);

    // The Remove method finds and removes the first node that 
    // that has the specified value.
    sentence->Remove("old");
    Display(sentence);

    // When the linked list is cast to ICollection(Of String),
    // the Add method adds a node to the end of the list. 
    sentence->RemoveLast();
    ICollection<String^>^ icoll = sentence;
    icoll->Add("rhinoceros");
    Display(sentence);

    // Create an array with the same number of elements as the
    // linked list.
    Console::WriteLine("\nCopy the list to an array.");
    array<String^>^ sArray = gcnew array<String^>(sentence->Count);
    sentence->CopyTo(sArray, 0);

    for each( String^ s in sArray )
    {
        Console::WriteLine(s);
    }

    // Release all the nodes.
    sentence->Clear();
}

//This code example produces the following output:
//
//the fox jumped over the dog
//sentence->Contains("jumped") = True
//today the fox jumped over the dog
//the fox jumped over the dog today
//the fox jumped over the dog yesterday
//yesterday the fox jumped over the dog
//the fox jumped over (the) dog
//the fox jumped over (the) lazy old dog
//the (fox) jumped over the lazy old dog
//the quick brown (fox) jumped over the lazy old dog
//the quick brown fox jumped over the lazy old (dog)
//Exception message: The LinkedList node belongs a LinkedList.
//the quick brown jumped over the lazy old fox (dog)
//Node "dog" is not in a list.
//the quick brown (dog) jumped over the lazy old fox
//the quick brown dog jumped over the lazy fox
//the quick brown dog jumped over the lazy rhinoceros
//
//Copy the list to an array.
//the
//quick
//brown
//dog
//jumped
//over
//the
//lazy
//rhinoceros
继承层次结构

System.Object
  System.Collections.Generic.LinkedList
线程安全

此类型的公共静态(在 Visual Basic 中为 Shared)成员是线程安全的。但不能保证任何实例成员是线程安全的。

只要不修改该集合,LinkedList 就可以同时支持多个阅读器。即便如此,从头到尾对一个集合进行枚举本质上并不是一个线程安全的过程。当出现枚举与写访问互相争用这种极少发生的情况时,必须在整个枚举过程中锁定集合。若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0

.NET Compact Framework

受以下版本支持:2.0
请参见

标记 :


Page view tracker