LeetCode link: https://leetcode.com/problems/copy-list-with-random-pointer/
Question Description:
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
- val: an integer representing Node.val
- random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.
Method:
- Create hash table, copy every node to hash table.
- Build relationship according to original linked list.
Code:
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if head is None:
return None
nodeDict = dict()
# First loop to copy all node
pointer = head
while pointer:
nodeDict[pointer] = Node(pointer.val, None, None)
pointer = pointer.next
# Second loop to copy relationship
pointer = head
while pointer:
if pointer.next:
nodeDict[pointer].next = nodeDict[pointer.next]
if pointer.random:
nodeDict[pointer].random = nodeDict[pointer.random]
pointer = pointer.next
return nodeDict[head]
本文介绍了一种解决LeetCode上复杂链表复制问题的方法,该链表节点包含一个额外的随机指针。通过使用哈希表,文章详细阐述了如何创建链表的深拷贝,包括两步:首先复制所有节点到哈希表,然后根据原始链表建立关系。

469

被折叠的 条评论
为什么被折叠?



