remove a node from the end of a linked list in csharp

To remove a node from the end of a linked list in C#, you can follow these steps:

  1. Traverse the linked list until you reach the second-to-last node. You can do this by starting from the head of the linked list and moving through the list until you reach the second-to-last node.

  2. Set the next pointer of the second-to-last node to null. This will remove the last node from the linked list.

  3. If the linked list only had one node, set the head of the linked list to null.

Here's the code:

main.cs
public void RemoveEndNode()
{
    if (head == null) return;

    if (head.next == null)
    {
        head = null;
        return;
    }

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

    secondLast.next = null;
}
288 chars
19 lines

In this code, head refers to the first node of the linked list. If head is null, this means that the linked list is empty and there is nothing to remove. If head.next is null, this means that the linked list only has one node, and that node should be removed.

The while loop traverses the linked list until secondLast points to the second-to-last node. The line secondLast.next = null; removes the last node from the linked list by setting the next pointer of the second-to-last node to null.

gistlibby LogSnag