Why my c code does not work, and it shows time limit exceed


  • 0
    Z
    struct ListNode* sortList(struct ListNode* head) {
    struct ListNode *pointer;
    pointer=head;
    int length=0;
    if (pointer==NULL || pointer->next==NULL) return head;
    else {
        while (pointer){
            length++;
            pointer=pointer->next;
        }
    }
    struct ListNode* ahead;
    ahead->next=head;
    for (int interval=1; interval<=length; interval=interval*2){
        struct ListNode *pre, *after, *p;
        p=ahead; pre=ahead->next; after=ahead->next;
        while (pre || after){
            int count=0;
            while (count<interval && after){
                after=after->next;
                count++;
            }
            int counta, countp;
            countp=0; counta=0;
            while (countp<interval && countp<interval && pre && after){
                if ((pre->val)>(after->val)){
                    p->next=after;
                    p=after;
                    after=after->next;
                    counta++;
                }else{
                    p->next=pre;
                    p=pre;
                    pre=pre->next;
                    countp++;
                }
            }
            while (pre && countp<interval){
                p->next=pre;
                p=pre;
                pre=pre->next;
                countp++;
            }
            while (after && counta<interval){
                p->next=after;
                p=after;
                after=after->next;
                counta++;
            }
            pre=after;
            p->next=after;
        }
    }
    return ahead->next;
    

    }


Log in to reply
 

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