从链表中删除节点 (C#)

Removing a node from a LinkedList (C#)

我创建了一个 LinkedList class 函数 delete 从列表中删除某个节点(如果找到的话),但是它不起作用:

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;
    }
    <...>
}

我想我需要做的就是找到节点并将其设置为下一个节点(因此该节点 "removed" 不在链表中),但事实并非如此。如果有人能帮助我,我将不胜感激!

编辑:忘了说我有一个链表。

EDIT2:我的新代码:

    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;
    }

您需要遍历列表直到下一个节点是您要删除的节点。然后设置当前为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;
    }
}

这当然假设您只想删除第一个匹配项。