my c++ solution(49ms)


  • 0
    W
    class Solution {
    public:
        void reorderList(ListNode* head) {
            if(!head) return;
            int n=0;
            ListNode* p = head;
            while(p){
                n++;
                p = p->next;
            }
            
            int k = (n+1)/2-1;
            p=head;
            for(int i=1; i<=k; ++i) p=p->next;
            reverseList(p);
    
            ListNode* q=head, *temp1, *temp2, *x;
            x = p->next;
            p->next = NULL;
            p = x;
            while(p){
                temp1 = q->next;
                temp2 = p->next;
                q->next = p;
                p->next = temp1;
                p = temp2;
                q = temp1;
            }
        }
    private:
        void reverseList(ListNode* head){
            if(!head->next) return;
            ListNode* pre, *cur, *next;
            pre = head;
            cur = head->next;
            next = cur->next;
            while(cur){
                cur->next = pre;
                pre = cur;
                cur = next;
                if(next) next = next->next;
            }
            head->next->next = NULL;
            head->next = pre;
        }
    };
    

Log in to reply
 

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