-
Notifications
You must be signed in to change notification settings - Fork 127
Open
Description
题目二中代码有误:
// 考虑头指针是否存在
if (preNode == null) {
pHead = next;
}
当头指针存在时,只是pHead = next;是无效的,因为java中是按值传递的,方法中无法修改实参pHead的值,只能修改pHead节点中的val和next属性。
正确的方式应该这样:
// 如果是头指针,就把next的值给它,并且让它的next指向next.next
if (preNode == null) {
head.val = next.val;
head.next = next.next;
next.next = null;
}
这是测试用例:
// 测试
public static void main(String[] args) {
ListNode listNode_1 = new ListNode(1);
ListNode listNode_2 = new ListNode(1);
ListNode listNode_3 = new ListNode(1);
ListNode listNode_4 = new ListNode(4);
ListNode listNode_5 = new ListNode(5);
listNode_1.next = listNode_2;
listNode_2.next = listNode_3;
listNode_3.next = listNode_4;
listNode_4.next = listNode_5;
print_listNode(listNode_1); // 删除前
deleteDuplication(listNode_1);
print_listNode(listNode_1); // 删除后
}
// 打印listNode(用作测试)
public static void print_listNode(ListNode listNode) {
while (listNode != null) {
System.out.print(listNode.val+" ");
listNode = listNode.next;
}
System.out.println();
}
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels