1
votes

I'm new to Linked Lists and I'm having trouble removing a specific object from a singly linked list. The method won't remove the first element in the list at all, yet it also seems to delete multiple nodes at once.

Remove Method:

public void remove(Element e)

{
    Node dummy = new Node(null);
    dummy.next = firstNode;
    Node temporary = dummy;
    while (temporary.next != null)
    {
        if (e.getString1().compareTo(temporary.next.getElement().getString1()) < 0)
        {
            temporary.next = temporary.next.next;
        }
        else
        {
            temporary = temporary.next;
        }
    }    
}

Private Node Class (and first Node in ElementList class)

Node firstNode = null; private class Node
{
    Element value;
    Node next = null;
    private Node(Element e)
    {
        this.value = e;
    }

    public Element getElement()
    {
        return value;
    }
}

Demo Method:

 list.add(vvv);
 list.add(eee);
 list.add(ddd);
 list.remove(eee);
 System.out.println(list); //<- Output: all three objects still appear
 list.remove(vvv);
 System.out.println(list); //<- Output: vvv is there, for some reason 
                                 eee and ddd are now gone
 list.remove(ddd);
 System.out.println("Break between last element and empty list");
 System.out.println(list); //<- Output: vvv is still there
1
Did you mean == 0 instead of < 0? - tsolakp

1 Answers

1
votes

You have at least two problems. Possibly more. Hard to tell without more complete code.

First: This was referenced in a comment on your question. This line:

if (e.getString1().compareTo(temporary.next.getElement().getString1()) < 0)

The comparison used here is likely not what you want. Please see the documentation of String.compareTo() (Javadoc).

Second: You never actually change the reference to firstNode (which, I'm assuming, you utilize everywhere to be the head of your list) in your remove() method. Of course vvv is going to stick around; you never change firstNode to point at anything other than that.

I'm suspecting this is homework, so I'm not going to provide code answers to the problems, but these should give you an indication of where your problems are. If this isn't homework; definitely use a built-in Java list vs. making your own.