【发布时间】:2018-07-08 11:12:08
【问题描述】:
我是链表的新手,在从单链表中删除特定对象时遇到问题。该方法根本不会删除列表中的第一个元素,但它似乎也一次删除了多个节点。
删除方法:
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;
}
}
}
私有节点类(和ElementList 类中的第一个Node)
Node firstNode = null; private class Node
{
Element value;
Node next = null;
private Node(Element e)
{
this.value = e;
}
public Element getElement()
{
return value;
}
}
演示方法:
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
【问题讨论】:
-
您的意思是
== 0而不是< 0?
标签: java list linked-list nodes singly-linked-list