Simple c++ solution using unordered_map (accepted)


  • 0
    O

    I know not optimal in time depending on efficiency of uordered_map lookup, but very simple and fast enough.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        void reorderList(ListNode *head) {
            if (!head) return;
            unordered_map<int, ListNode*> Nodemap;
            int i=0, j=0;
            Nodemap[i] = head; head = head->next;
            while (head){i++; Nodemap[i] = head; head = head->next;}
            while (i>j+1){Nodemap[j]->next = Nodemap[i]; j++; Nodemap[i]->next = Nodemap[j]; i--;}
            Nodemap[i]->next = NULL;
        }
    };

  • 0
    S

    your solution use unoredered_map to all the pointers, using O(N) extra space, is it satisfy the conditions ?


Log in to reply
 

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