Open In App
Related Articles

C# | Get the last node of the LinkedList<T>

Improve Article
Improve
Save Article
Save
Like Article
Like

LinkedList<T>.Last property is used to get the last node of the LinkedList<T>.

Syntax:

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

Return Value: The last LinkedListNode<T> of the LinkedList<T>.

Below given are some examples to understand the implementation in a better way:

Example 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<String> myList = new LinkedList<String>();
  
        // 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");
    }
}


Output:

E

Example 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<int> myList = new LinkedList<int>();
  
        // To get the last node of the LinkedList
        if (myList.Count > 0)
            Console.WriteLine(myList.Last.Value);
        else
            Console.WriteLine("LinkedList is empty");
    }
}


Output:

LinkedList is empty

Note:

  • LinkedList accepts null as a valid Value for reference types and allows duplicate values.
  • If the LinkedList is empty, the First and Last properties contain null.
  • Retrieving the value of this property is an O(1) operation.

Reference:


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 01 Feb, 2019
Like Article
Save Article
Previous
Next
Similar Reads