Removing a node from a LinkedList (C#)

5.4k views Asked by At

I created a LinkedList class with a function delete to remove a certain node from the list if found, however it's not working:

public class LinkedList
{
    public Node head;
    <...>
    public void delete(string n)
    {
        Node x = search(n); //returns the node to delete or null if not found
        if (x != null)
            x = x.next;
    }
    <...>
}

I figured all I needed to do is find the node and set it to the next one (so the node is "removed" out of the linked list), however it's not. If anyone could help me out it'd be much appreciated!

EDIT: Forgot to mention I have a single linked list.

EDIT2: My new code:

    public void delete(string n)
    {
        Node x = head;
        while (x != null && x.name != n)
        {
            if (x.next.name == n)
                x.next = x.next.next;
            x = x.next;
        }
        if (x != null)
            x = null;
    }
1

There are 1 answers

1
juharr On BEST ANSWER

You'll want to loop through the list until the next node is the one you want to delete. Then set the current to the next nodes next node.

public void Delete(string value)
{
    if (head == null) return;

    if (head.Value == value)
    {
        head = head.Next;
        return;
    }

    var n = head;
    while (n.Next != null)
    {
        if (n.Next.Value == value)
        {
            n.Next = n.Next.Next;
            return;
        }

        n = n.Next;
    }
}

This of course assumes you only want to delete the first match.