an error:keyerror,
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
if head==None:
return None
cur=head.next
ret=Node(head.val,None,None)
pre=ret
dic=dict()
dic[ret]=head
while cur!=None:
node=Node(cur.val,None,None)
pre.next=node
dic[cur]=node
pre=node
cur=cur.next
node=head
cur=ret
while cur:
if node.random==None:
cur.random=None
else:
cur.random=dic[node.random] #
cur=cur.next
node=node.next
return ret
Another method: insert a node in the middle of 2 node in original list
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
"""
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
if head==None:
return None
#insert a new node in the middle
cur=head
while cur:
node=Node(cur.val,None,None)
tmp=cur.next
cur.next=node
node.next=tmp
cur=cur.next.next
#random pointer hanle
cur=head
while cur:
if cur.random:
cur.next.random=cur.random.next
cur=cur.next.next
#seperate the target deep copy list
cur=head
res=cur.next
while cur:
node=cur.next
cur.next=cur.next.next
if node.next:
node.next=node.next.next
cur=cur.next
return res