Help!


  • 0
    W

    Where did I go wrong?
    '''

    typedef struct ListNode ListNode;

    ListNode* merge(ListNode* l1,ListNode* l2)
    {
    ListNode l = (ListNode)malloc(sizeof(ListNode));
    ListNode *p = l;
    while(!l1 && !l2)
    {
    if(l1->val < l2->val)
    {
    p->next = l1;
    l1 = l1->next;
    }
    else
    {
    p->next = l2;
    l2 = l2->next;
    }
    p = p->next;
    }
    if(l1 != NULL)
    {
    p->next = l1;
    }
    if(l2 != NULL)
    {
    p->next = l2;
    }
    return l->next;
    }

    ListNode* sortList(ListNode* head) {
    if(head == NULL || head->next == NULL)
    {
    return head;
    }
    ListNode *slow = head,*fast = head,*pre = NULL;

    //先将链表分成两个部分
    while(fast != NULL || fast->next != NULL)
    {
        pre = slow;
        slow = slow->next;
        fast = fast->next->next;
    }
    
    pre->next = NULL;
    
    //再对这两个部分进行排序
    ListNode *l1 = sortList(head);
    ListNode *l2 = sortList(slow);
    
    //最后将其合并
    
    return merge(l1,l2);
    

    }
    '''


Log in to reply
 

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