A TLE C solution, but I think it sholud be correct. Who knows what's wrong?


  • 0
    S
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
     
    static void load_p1p2(struct ListNode *head, struct ListNode **p1, struct ListNode **p2)
    {
        *p1 = head->next;
        
        while((*p1)->next->next)
        {
            *p1 = (*p1)->next;
        }
        
        *p2 = (*p1)->next;
    }
     
    void reorderList(struct ListNode *head) {
                                        
        if(head && head->next && head->next->next)
        {
            struct ListNode *phead = head,*p1,*p2;
            
            do{
                load_p1p2(phead, &p1, &p2);
                p2->next = phead->next;
                phead->next = p2;
                phead = p2->next;
            }while(phead->next && phead->next != p1);
        }
        
        return head;
    }

  • 0
    K

    Let Consider length of list=N. Then your solution is O (N x N). You can do it in O (N) using extra memory of Order(N x Size of one Node). You can do it even without using extra memory.


Log in to reply
 

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