C++ recursion solution


  • 0
    W
        /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    private:
        map<ListNode*, ListNode*> pre;
    public:
        ListNode* f(ListNode *head, ListNode *tail) {
            if(head == NULL)    return NULL;
            if(head->next == NULL || head->next->next == NULL)  return head;        //1 or 2 elems
            ListNode *p1 = pre[tail];
            p1->next = NULL;
            tail->next = f(head->next,p1);
            head->next = tail;
            return head;
        }
        void reorderList(ListNode *head) {
            if(head == NULL)    return;
            if(head->next == NULL || head->next->next == NULL)  return;        //1 or 2 elems
            ListNode *p1 ,*p2;
            p1 = head;
            p2 = head->next;
            while(p2 != NULL)
            {
                pre[p2] = p1;
                p1 = p1->next;
                p2 = p2->next;
            }
            f(head, p1);
        }
    };

Log in to reply
 

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