What 's the right solution to "Last executed input:{}" ?


  • 2
    T

    If I got it right, the error "last executed input {} " means that the input is an empty list. So I wrote this:

    if(head->next == NULL || head == NULL) return head;
    

    However, the online judge doesn't stop yelling "last executed input {}". I've no idea about why the above code didn't work. To unfold the whole story, I put my code here.

    ListNode * merge(ListNode * leftHalf, ListNode * rightHalf){
        ListNode * result;
        while(leftHalf != NULL || rightHalf != NULL){
            if(leftHalf != NULL && rightHalf != NULL){
                if(leftHalf->val < rightHalf->val){
                    result->next = leftHalf;
                    leftHalf = leftHalf->next;
                }else{
                    result->next = rightHalf;
                    rightHalf = rightHalf->next;
                }
            }else if(leftHalf == NULL && rightHalf != NULL){
                result->next = rightHalf;
                rightHalf = rightHalf->next;
            }else{
                result->next = leftHalf;
                leftHalf = leftHalf->next;
            }
        }
    }
    
    ListNode *sortList(ListNode *head) {
        if(head->next == NULL || head == NULL) return head;
    
        ListNode * pLeft = head;
        ListNode * pRight = head;
    
        while( (pRight->next != NULL) && (pRight->next->next != NULL)){
            pLeft = pLeft->next;
            pRight = pRight->next->next;
        }
        pRight = pLeft->next;
        pLeft->next = NULL;  
        pLeft = head;
    
        ListNode * leftHalf = sortList(pLeft);
        ListNode * rightHalf = sortList(pRight);
        ListNode * result = merge(leftHalf, rightHalf);
        return result;
    }

  • 0
    T

    I found out where the problems were.

    1. If head is null, it has no field called next. Therefore, the operation head->next will cause segmentation fault, since it is checked first. To clear that problem, the code "if(head->next == NULL || head == NULL)" should be corrected to "if (head == NULL || head->next == NULL)".
    2. A more serious problem is that I forgot to move result to the next node. And the value returned was totally wrong.

  • 4
    J

    I think "input {} " means "head" is null instead of "head.next" is null. if "head" is null, "head.next" is not existent. Am I right?


  • 0
    T

    Yeah, exactly. I put the problems and the solutions in my previous comment. Thanks, jian.he.587. :)


Log in to reply
 

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