Skip to content

删除链表的节点 代码有误 #7

@tuziang-com

Description

@tuziang-com

地址: 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();
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions