Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
communitycreator

How to add a node to the end of a linked list in C#

Surabhi Sharma

The LinkedList<T> generic class in the System.Collections.Generic namespace provides the AddLast() method, which is used to add a node to the end of a linked list.

Syntax

public System.Collections.Generic.LinkedListNode<T> AddLast (T value);
  • It takes the value T as input and returns a new LinkedListNode<T> that contains the passed input value.
  • It has an overload available which takes LinkedListNode<T> as input and adds it to the end of the list.

Things to note

  • This method is an O(1)O(1) operation.

  • LinkedList<T> accepts null as a valid reference type value.

  • LinkedList<T> allows duplicate values as well.

  • For an empty linked list, the new node becomes the first and the last node.

Adding a node to the end of the list using AddLast()

Code

In the code below, we created a linked list of strings and added the names of a few months to it. The linked list contains four strings: January, February, March, and April.

We have also created a Print() helper method to display the linked list nodes.

Now, we call the AddLast() method to pass May as the argument on this linked list. It adds the node at the end of the list. We can see that the last node is shown as May in the output.

We again call the AddLast() method to pass June as the argument, and it adds the node at the end of the list. We can see that the last node is shown as June in the output.

Please note that the LinkedList<T> class is maintained internally as a doubly-linked list and AddLast() is an O(1)O(1) operation.

using System;
using System.Collections.Generic;

class LinkedListAddition
{
    static void Main()
    {
        LinkedList<string> monthList = new LinkedList<string>();
        monthList.AddLast("January");
        monthList.AddLast("February");
        monthList.AddLast("March");
        monthList.AddLast("April");

        Console.WriteLine("LinkedList Elements");
        Print(monthList);

        monthList.AddLast("May");
        Console.WriteLine("LinkedList Elements After AddLast('May')");
        Print(monthList);

        monthList.AddLast("June");
        Console.WriteLine("LinkedList Elements After AddLast('June')");
        Print(monthList);
    }

    private static void Print(LinkedList<string> list)
    { 
        foreach (var node in list)
        {
            Console.Write(node + ", ");
        }
        Console.WriteLine("\n");        
    }
}

RELATED TAGS

c#
communitycreator
RELATED COURSES

View all Courses

Keep Exploring