# Definition for singly-linked list with a random pointer. classRandomListNode: def__init__(self, x): self.label = x self.next = None self.random = None
classSolution: # @param head, a RandomListNode # @return a RandomListNode defcopyRandomList(self, head): ifNone == head: returnNone save_list = [ ] p1 = head whileNone != p1: save_list.append(p1) p1 = p1.next new_head = RandomListNode(-1) new_head.next = head first = new_head second = head copy_head = RandomListNode(-1) copy_first = copy_head copy_second = None whileNone != first: copy_second = RandomListNode(second.label) ifNone != second elseNone copy_first.next = copy_second copy_first = copy_first.next first = first.next ifNone != second: second = second.next
p1 = head p1_tail = head.next p2 = copy_head.next whileNone != p1: p1_tail = p1.next p1.next = p2 p2.random = p1 p1 = p1_tail p2 = p2.next p2 = copy_head.next #p1 = head whileNone != p2: p2.random = p2.random.random.nextifNone != p2.random.random elseNone #p1.next = p1.next.next.random if None != p1.next.next else None # may broken the previous p1.next, so have to save ori list p2 = p2.next #p1 = p1.next len_save_list = len(save_list) for i inrange(0, len_save_list - 1): save_list[i].next = save_list[i + 1] save_list[len_save_list - 1].next = None return copy_head.next