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
== 0instead of< 0? - tsolakp