请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
示例 1:
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:
输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]
示例 3:
输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]
示例 4:
输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 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: 'Optional[Node]') -> 'Optional[Node]':# if head is None:# return None# cur = head# next = None# while cur is not None: # 1 -> 2 变化成 1 -> 1' -> 2 -> 2'# next = cur.next# cur.next = Node(cur.val)# cur.next.next = next# cur = next# cur = head# curcopy = None# while cur is not None: # 一对一对取出来连random指针# next = cur.next.next# curcopy = cur.next# curcopy.random = cur.random.next if cur.random is not None else None# cur = next# res = head.next# cur = head# while cur is not None: # 分离链表# next = cur.next.next# curcopy = cur.next# cur.next = next# curcopy.next = next.next if next is not None else None# cur = next# return reshashmap = dict()cur = headwhile cur is not None:hashmap[cur] = Node(cur.val)cur = cur.nextcur = headwhile cur is not None:hashmap.get(cur).next = hashmap.get(cur.next)hashmap.get(cur).random = hashmap.get(cur.random)cur = cur.nextreturn hashmap.get(head)
class Solution:def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':if head is None:return Nonecur = headnext = Nonewhile cur is not None: # 1 -> 2 变化成 1 -> 1' -> 2 -> 2'next = cur.nextcur.next = Node(cur.val)cur.next.next = nextcur = nextcur = headcurcopy = Nonewhile cur is not None: # 一对一对取出来连random指针next = cur.next.nextcurcopy = cur.nextcurcopy.random = cur.random.next if cur.random is not None else Nonecur = nextres = head.nextcur = headwhile cur is not None: # 分离链表next = cur.next.nextcurcopy = cur.nextcur.next = nextcurcopy.next = next.next if next is not None else Nonecur = nextreturn res
