add a node to the end of a linked list in csharp

To add a node to the end of a linked list in C#, you should first check if the linked list is empty or not. If it is empty, you can just create a new node and set it as the head of the linked list. If it is not empty, you should traverse to the end of the linked list and then add the new node.

Here's the code to add a node to the end of a linked list in C#:

main.cs
public class Node
{
    public int data;
    public Node next;
    public Node(int data)
    {
        this.data = data;
        this.next = null;
    }
}

public class LinkedList
{
    private Node head;

    public void AddToEnd(int data)
    {
        Node newNode = new Node(data);

        if (head == null)
        {
            head = newNode;
            return;
        }

        Node lastNode = head;
        while (lastNode.next != null)
        {
            lastNode = lastNode.next;
        }

        lastNode.next = newNode;
    }
}
550 chars
35 lines

Here, the Node class is used to create a new node and the LinkedList class is used to perform various operations on the linked list.

The AddToEnd method takes an integer data argument and creates a new node with this data. If the linked list is empty, then the new node is set as the head of the linked list. Otherwise, the method traverses to the end of the linked list using a while loop and then adds the new node.

gistlibby LogSnag