lydia bi
lydia bi

Reputation: 31

How do i write a method that removes specific object from linked list?

i didn't succeed to remove specific item from linked list,the method is - public void removeFromList(string itemtoremove, LinkedList List).

How do i write method that removes specific item from linked list?

my code is:

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)
             ???

        }

    }

}

Upvotes: 0

Views: 90

Answers (1)

NathanDykstra
NathanDykstra

Reputation: 85

Your method already has a problem before you even implement the algorithm. You are skipping the head node. You also don't need to pass the linked list in as a parameter to the instance method.

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

}

Upvotes: 1

Related Questions