Coding-Interviews
Coding-Interviews copied to clipboard
删除链表的节点 代码有误
地址: https://github.com/todorex/Coding-Interviews/blob/master/notes/%E5%88%A0%E9%99%A4%E9%93%BE%E8%A1%A8%E8%8A%82%E7%82%B9.md
题目二中代码有误:
// 考虑头指针是否存在
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();
}
题目一也有问题
if (toBeDeleted.next != null) {
// 要删除的节点不是尾节点
ListNode next = toBeDeleted.next;
toBeDeleted.val = next.val;
toBeDeleted.next = next.next;
toBeDeleted.next = null;
}
最后一行的toBeDeleted.next = null;
将会导致toBeDeleted后没有节点。
根据书上这里最后一行可以改为
next = null;
不过因为jvm的垃圾回收机制,不加这一句也没问题。
测试用例:
// 测试
public static void main(String[] args) {
ListNode listNode_1 = new ListNode(1);
ListNode listNode_2 = new ListNode(2);
ListNode listNode_3 = new ListNode(3);
ListNode listNode_4 = new ListNode(4);
listNode_1.next = listNode_2;
listNode_2.next = listNode_3;
listNode_3.next = listNode_4;
print_listNode(listNode_1); // 删除前
deleteNode(listNode_1, listNode_2);
print_listNode(listNode_1); // 删除后
/* deleteNode(listNode_1, listNode_3);
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();
}