Why this code has runtime error in OJ while works well in Xcode?


  • 0
    H

    My idea is to skip the nodes whose values smaller than x and put the nodes whose values greater or equal to x to the tail of the linklist. I got a runtime error for the test case ( [1,1],0 ).

    ListNode* partition(ListNode* head, int x) {
            if(!head) return NULL;
            ListNode* last = head;
            int len = 0;
            ListNode* dummy;
            int f = 0;
            while(last->next){
                last = last->next;
                len++;
                if(f == 0 && last->val < x){
                    dummy = last;
                    f++;
                }
            }
            if(len == 0) return head;
            ListNode* cur = head;
            ListNode* pre = NULL;
            
            for(int i = 0; i <= len; i++){
                if(cur->val < x){
                    pre = cur;
                    cur = cur->next;
                }
                else if(pre == NULL){
                    last->next = cur;
                    pre = cur;
                    cur = cur->next;
                    pre->next = NULL;
                    pre = NULL;
                    last = last->next;
                }
                else{
                    last->next = cur;
                    pre->next = cur->next;
                    ListNode* tmp = cur;
                    cur = cur->next;
                    tmp->next = NULL;
                }
            }
            return dummy==NULL?cur:dummy;
        }

Log in to reply
 

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