题目链接: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 = nextself.random = random"""class Solution:def copyRandomList(self, head: 'Node') -> 'Node':if head is None:return Nonetemp = headwhile temp is not None:new_node = Node(temp.val, temp.next)temp.next = new_nodetemp = new_node.nexttemp = headwhile temp is not None:if temp.random is not None:temp.next.random = temp.random.nexttemp = temp.next.nexttemp = headret = head.nextcur = retwhile cur.next:temp.next = cur.nexttemp = temp.nextcur.next = temp.nextcur = cur.nexttemp.next = Nonereturn ret
