[how about this] recursive call, track visited node with hashtable


  • 1
    G
    class Solution {
    public:
        RandomListNode *copyRandomList(RandomListNode *head) {
            unordered_map<RandomListNode *, RandomListNode*> visitTable;
            return copyRandomList(head, visitTable);
        }
    private:
        RandomListNode *copyRandomList(RandomListNode *head, unordered_map<RandomListNode *, RandomListNode*> &visitTable) {
            if (!head) return head;
            if (visitTable.count(head)) return visitTable[head];
            RandomListNode *dup = new RandomListNode(head->label);
            visitTable[head] = dup;
            dup->next = copyRandomList(head->next, visitTable);
            dup->random = copyRandomList(head->random, visitTable);
            return dup;
        }
    };

Log in to reply
 

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