Problem link:
http://oj.leetcode.com/problems/copy-list-with-random-pointer/
Deepcopy a linked list with random pointer, realy simple problem, solved in three steps using a hash map:
- Create a new head, duplicating the head (return NULL for case head==NULL), map key=p1 with value=p2.
- Let p1 point to head and p2 point to the new head. For each p1.next != NULL, duplicate p1.next and assign the new created node to p2.next, then move p1 and p2 to the next node and map them.
- Scan each node of the old list again. For each node p, if p.random != None, set hash_map[p].random = hash_map[p.random].
The following code is my python solution accepted by oj.leetcode.
# 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):
if head is None:
return None
mapping = {}
# Duplicate the head
new_head = RandomListNode(head.label)
# Duplicate the node and next pointer
p1 = head
p2 = new_head
mapping[p1] = p2
while p1.next is not None:
p2.next = RandomListNode(p1.next.label)
p2 = p2.next
p1 = p1.next
mapping[p1] = p2
# Duplicate the random pointer
p1 = head
while p1 is not None:
r1 = p1.random
if r1 is not None:
mapping[p1].random = mapping[r1]
p1 = p1.next
# Return
return new_head