题目链接:https://leetcode-cn.com/problems/copy-list-with-random-pointer/
难度:中等
描述:
给你一个长度为n的链表,每个节点包含一个额外增加的随机指针random,该指针可以指向链表中的任何节点或空节点。
构造这个链表的深拷贝。深拷贝应该正好由n个全新节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的next指针和random指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
提示:
节点数:[0, 1000]
题解
迭代
遍历链表,复制每个节点(复制的节点的random = None),将复制的节点插入到原节点的后面:
再次遍历,添加复制节点的random指针
最后分离两个链表
"""# 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]':cur = headwhile cur is not None:new_node = Node(cur.val, cur.next, None)cur.next = new_nodecur = cur.next.nextcur = headwhile cur is not None:if cur.random is not None:cur.next.random = cur.random.nextcur = cur.next.nextdummy = Node(0, None, None)temp = dummycur = headwhile cur is not None:temp.next = cur.nexttemp = temp.nextcur.next = cur.next.nextcur = cur.nextreturn dummy.next
哈希表
建立一个哈希表,遍历链表,使key = original_node,value = new_node
再次遍历链表,给new_node加上next 和random
"""# 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 Nonenode_map = {}cur = headwhile cur is not None:new_node = Node(cur.val, None, None)node_map[cur] = new_nodecur = cur.nextcur = headwhile cur is not None:if cur.next is not None:node_map[cur].next = node_map[cur.next]if cur.random is not None:node_map[cur].random = node_map[cur.random]cur = cur.nextreturn node_map[head]
