138. 复制带随机指针的链表
解法
c++
//c++
class Solution {
public:
unordered_map<Node*,Node*> cachedNode;
Node* copyRandomList(Node* head) {
if(head==nullptr){
return nullptr; }
if(!cachedNode.count(head)){
//复制头节点
Node *headNew=new Node(head->val);
cachedNode[head]=headNew;
headNew->next=copyRandomList(head->next);
headNew->random=copyRandomList(head->random);
}
return cachedNode[head];
}
};
python
#python
class Solution:
def __init__(self):
self.cach={ }
def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
if head is None:
return None
#如果head不在里面,创建节点。在就查询哈希表
if head not in self.cach:
headnext=Node(head.val)
self.cach[head]=headnext
headnext.next=copyRandomList(head.next)
headnext.random=copyRandomList(head.random)
return self.cach[head]