📜  C#|获取LinkedList的最后一个节点<T>

📅  最后修改于: 2021-05-29 20:01:59             🧑  作者: Mango

LinkedList < T > .Last属性用于获取LinkedList 的最后一个节点。

句法:

public System.Collections.Generic.LinkedListNode Last { get; }

返回值: LinkedList < T >的最后一个LinkedListNode < T >

下面给出了一些示例,以更好地理解实现:

范例1:

// C# code to get the last
// node of the LinkedList
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a LinkedList of Strings
        LinkedList myList = new LinkedList();
  
        // Adding nodes in LinkedList
        myList.AddLast("A");
        myList.AddLast("B");
        myList.AddLast("C");
        myList.AddLast("D");
        myList.AddLast("E");
  
        // To get the last node of the LinkedList
        if (myList.Count > 0)
            Console.WriteLine(myList.Last.Value);
        else
            Console.WriteLine("LinkedList is empty");
    }
}

输出:

E

范例2:

// C# code to get the last
// node of the LinkedList
using System;
using System.Collections;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
        // Creating a LinkedList of Integers
        LinkedList myList = new LinkedList();
  
        // To get the last node of the LinkedList
        if (myList.Count > 0)
            Console.WriteLine(myList.Last.Value);
        else
            Console.WriteLine("LinkedList is empty");
    }
}

输出:

LinkedList is empty

笔记:

  • LinkedList接受null作为引用类型的有效值,并允许重复的值。
  • 如果LinkedList为空,则FirstLast属性包含null
  • 检索此属性的值是O(1)操作。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.linkedlist-1.last?view=netframework-4.7.2