如何编写从链表中删除特定对象的方法?

时间:2015-09-18 15:15:50

标签: c# methods linked-list

我没有成功从链表中删除特定项,方法是 - 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)
             ???

        }

    }

}

1 个答案:

答案 0 :(得分:1)

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

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

}