首页 > 解决方案 > java无限链表问题

问题描述

所以我正在解决这个问题:给定一个排序链表的头部,删除所有重复项,使每个元素只出现一次。返回排序好的链表。测试示例为[1,1,2]。

public static class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public static ListNode deleteDuplicates(ListNode head) {
    ListNode l3=new ListNode(9);
    ListNode l4 = l3;
    if (head==null||head.next==null){
      return head;
    }
    while (head.next!=null){
        if(head.val== head.next.val){
            head=head.next;
            l3.next=head;
        }else {
            l3.next=head;
            head=head.next;
//when I debug until this line,it will creat infinite list like[1,1,1,1,.......,1,1,1]
        }
        l3=l3.next;
    }
    return l4.next;
}

所以正如你在代码中看到的,为什么当测试示例是[1,1,2]时它会创建无限列表?

标签: javalist

解决方案


推荐阅读