我无法让我的程序删除链接列表中的最后一个节点或唯一的节点。它将删除任何其他节点。该程序允许用户输入整数并删除它们。在此先感谢您的帮助。
// This method finds the value requested in the Linked List.
public Node find(Node head, Comparable value2){
if (head == null )
{
System.out.println("The list is empty");
return null;
}
Node pointer = head;
while (pointer != null)
{
if (pointer.data.compareTo(value2)>=0)
{
Node delNode = pointer;
System.out.print("Found it. Deleting " + delNode.data + "\n");
return delNode;
}
pointer = pointer.next;
}
return null;
}
// This method deletes a given value from the linked list.
public void delete(Node head, Comparable value2){
Node delNode;
delNode = find(head, value2);
if (delNode== null)
{
System.out.println("The value: " + value2 + " does not exist");
print(head);
}
else
{
if (delNode.next == null)
{
System.out.println("Trying to delete last");
delNode = null;
print(head);
}
else{
delNode.data = delNode.next.data;
Node temp = delNode.next.next;
delNode.next = null;
delNode.next = temp;
print(head);
}
}
return;
}
我以为 if (delNode.next== null) {delNode = null} 会这样做吗?