LeetCode 138 Copy List with Random Pointer (C++, Python)
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
Solution C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */ class Solution { public: RandomListNode *copyRandomList(RandomListNode *head) { unordered_map<RandomListNode*, RandomListNode*> um; um[NULL] = NULL; RandomListNode* node = head; RandomListNode* copyhead = NULL; while (node) { RandomListNode* copy = new RandomListNode(node->label); if (copyhead == NULL) copyhead = copy; copy->next = node->next; copy->random = node->random; um[node] = copy; node = node->next; } node = copyhead; while (node) { node->next = um[node->next]; node->random = um[node->random]; node = node->next; } return copyhead; } }; |
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | # Definition for singly-linked list with a random pointer. # class RandomListNode: # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution: # @param head, a RandomListNode # @return a RandomListNode def copyRandomList(self, head): nodemap = {None:None} node = head copyhead = None while node: copy = RandomListNode(node.label) if copyhead is None: copyhead = copy nodemap[node] = copy copy.next = node.next copy.random = node.random node = node.next node = copyhead while node: node.next = nodemap[node.next] node.random = nodemap[node.random] node = node.next return copyhead |