我需要此方法删除的帮助。我已经测试了该程序,不幸的是该方法根本不起作用,在我打印出大小后尝试删除该人后,大小没有变化。任何指导
public boolean delete(String name) {
Node p = head;
if( p == null) {
size--;
return true;
}else {
Node temp = p;
int comparison;
while(temp.next != null) {
comparison = temp.person.name.compareTo(name);
if(comparison == 0) {
temp.next = temp.next.next;
size--;
return true;
} else {
temp = temp.next;
}
}
}return false;
}
在您的 hile-loop 中使用检查temp.next != null
,应该使用temp != null
并跟踪上一个以链接到下一个prev.next = temp.next;
,试试这个:
static boolean remove(String name) {
if (head == null)
return false;
if (head.person.name.compareTo(name) == 0) {
head = head.next;
size--;
return true;
}
Node current = head.next;
Node prev = head;
while (current != null) {
if (current.person.name.compareTo(name) == 0) {
prev.next = current.next;
current = null;
size--;
return true;
}
prev = current;
current = current.next;
}
return false;
}