题目链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
难度:中等
描述:
请实现 copyRandomList
函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next
指针指向下一个节点,还有一个 random
指针指向链表中的任意节点或者 null
。
题解
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if head is None:
return None
temp = head
while temp is not None:
new_node = Node(temp.val, temp.next)
temp.next = new_node
temp = new_node.next
temp = head
while temp is not None:
if temp.random is not None:
temp.next.random = temp.random.next
temp = temp.next.next
temp = head
ret = head.next
cur = ret
while cur.next:
temp.next = cur.next
temp = temp.next
cur.next = temp.next
cur = cur.next
temp.next = None
return ret