Please Help Me! LTE for [4,19,14,5,-3,1,8,5,11,15] JAVA Can't Understand WhyTAT


  • 0
    B
    public ListNode insertionSortList(ListNode head) {
        ListNode dummy = new ListNode(0);
        ListNode pre = dummy;
        pre.next = head;
        ListNode cur = head;
        while(cur!=null&&cur.next!=null){
            ListNode next = cur.next;
            if(cur.val > next.val){
                //find the right position for next before cur
                ListNode tmp = dummy.next;
                ListNode cur_next = next.next;
                while(tmp.val<next.val) {pre =tmp;tmp = tmp.next;}
                pre.next = next;
                next.next = tmp;
                cur.next = cur_next;
                
            }
            else
                cur = next;
        }
        return dummy.next;
    }

  • 0
    L

    This line goes into infinite loop, that's the problem. When tmp == 4, next ==8, since 4 and 1 points to each other and both less than 8, tmp = tmp.next; would make tmp jumps between 4 and 1 infinitely.

    while(tmp.val<next.val) {pre =tmp;tmp = tmp.next;}
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.