具有随机指针的链表是一种特殊的链表结构,其中每个节点除了包含数据和一个指向下一个节点的指针外,还包含一个指向链表中任意节点或者null
的随机指针。这种结构增加了链表的复杂性,因为它需要在复制时正确地处理这些随机指针。
null
的随机指针。class Node:
def __init__(self, val, next=None, random=None):
self.val = val
self.next = next
self.random = random
def copyRandomList(head):
if not head:
return None
# Step 1: Create new nodes and insert them into the original list
current = head
while current:
new_node = Node(current.val, current.next)
current.next = new_node
current = new_node.next
# Step 2: Set the random pointers for the new nodes
current = head
while current:
if current.random:
current.next.random = current.random.next
current = current.next.next
# Step 3: Split the list into two lists
new_head = head.next
current = head
while current:
new_node = current.next
current.next = new_node.next
if new_node.next:
new_node.next = new_node.next.next
current = current.next
return new_head
通过上述步骤和代码示例,可以有效地实现具有随机指针的链表的深层副本,同时避免常见的问题。