My C++ Recursive solution


  • 1
    B
    class Solution {
    public:
        void Reverse(ListNode *head) {
            if(head==NULL) return;
            Reverse(head->next);
            if(stop) return;
            //insert node from head
            if(ahead!=head) {
                pre ->next = ahead;
                ahead = ahead->next;
                pre=pre->next;
            }
            //insert node from tail
            pre->next = head;
            pre=pre->next;
            pre->next = NULL;
            //if meet stop
            if(ahead ==head) {
               stop = true;
            }
        }
        void reorderList(ListNode *head) {
            ListNode fakeHead(-1);
            fakeHead.next = head;
            pre = &fakeHead;
            ahead = head;
            stop = false;
            Reverse(head);
        }
    private:
        ListNode * pre ;
        ListNode * ahead;
        bool stop;
    };

Log in to reply
 

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