我如何写一个方法,从链表中删除特定的对象

本文关键字:删除 对象 链表 何写一 方法 | 更新日期: 2023-09-27 18:13:16

我没有成功地从链表中删除特定的项目,方法是- public void removeFromList(string itemtoremove, LinkedList list)

我如何写方法,从链表中删除特定的项目?

我的代码是:
public class Node
{
    public Node next; //saves the adress
    public Person data; //saves the person
}
public class LinkedList  
{   
    private Node head; //starts from the begging
    public void AddFirst(Person data)  
    {
        Node toAdd = new Node();
        toAdd.data = data; // in data he saves the object
        toAdd.next = head;
        head = toAdd;
    }
    public void removeFromList(string itemtoremove, LinkedList List) // 
    {
        Node current = head;
        Node current1 = current.next;
        while (current1 != null)
        {
            if (current1.data.instrument == itemtoremove)
             ???
        }
    }
}

我如何写一个方法,从链表中删除特定的对象

在实现算法之前,您的方法已经存在问题。你正在跳过头节点。您也不需要将链表作为参数传递给实例方法。

public void removeFromList(string itemtoremove)
{
    Node previousNode = null;
    Node current = head;
    while (current != null) //starting with current1 would ignore the head node
    {
        // we found a match
        if (current.data.instrument == itemtoremove){
            // head node is treated slightly differently
            if(current == head){
                // set the next node to the new head
                head = current.next;
                // set to null so GC can clean it up
                current = null;
                return;
            }
            else {
                //update the previous node's link
                previousNode.next = current.next;
                current = null;
                return;
            }
        }
        // move on to the next
        previousNode = current;
        current = current.next;
    }
}