leetcode138

138. Copy List with Random Pointer

Description

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.

Idea

Clone problem is always involved with hashmap which store the mapping from original nodes to new nodes.

Code

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
33
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None

class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
if not head:
return None

# copy node (label) and create the mapping
cur = head
map_ = {}
while cur:
map_[cur] = RandomListNode(cur.label)
cur = cur.next

# traverse raw list and copy the relation (next and random)
cur = head
while cur:
if cur.next:
map_[cur].next = map_[cur.next]
if cur.random:
map_[cur].random = map_[cur.random]
cur = cur.next

return map_[head]