Title Description
A complex input list (each node has a node value, and two pointers, one pointing to the next node, a special pointer to any other node), returns a value after the head of the list replication complex. (Note that the output results do not return parameter node reference, otherwise the program will return empty sentenced questions directly)
Violence to solve:
First traverse from beginning to end, a new random pointer for the empty list. We were all kept in order with the two nodes in two lists list.
Then traverse from beginning to end, according to a random position in the original list of list, the linked list to the new random reference imparting respective nodes.
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
if not pHead:
return None
node = RandomListNode(pHead.label)
head = node
pHead_s = pHead
nodes = [pHead]
nodes_copy = [node]
pHead = pHead.next
while pHead:
node.next = RandomListNode(pHead.label)
node = node.next
nodes.append(pHead)
nodes_copy.append(node)
pHead = pHead.next
head_s = head
while pHead_s:
if pHead_s.random:
head_s.random = nodes_copy[nodes.index(pHead_s.random)]
pHead_s = pHead_s.next
head_s = head_s.next
return head
optimization:
The time complexity of the above-violence is O (n ^ 2), the spatial complexity is O (n)
Read an answer on the cattle off, time complexity is O (n), space complexity is O (1)
class Solution:
def Clone(self, pHead):
pHead_s = pHead
while pHead_s:
temp = pHead_s.next
pHead_s.next = RandomListNode(pHead_s.label)
pHead_s.next.next = temp
pHead_s = pHead_s.next.next
pHead_s = pHead
while pHead_s:
if pHead_s.random:
pHead_s.next.random = pHead_s.random.next
pHead_s = pHead_s.next.next
pHead_s = pHead
head_s = pHead_s.next
head = head_s
while head_s.next:
pHead_s.next = pHead_s.next.next
head_s.next = head_s.next.next
pHead_s = pHead_s.next
head_s = head_s.next
return head