题解中有位大佬说:random指针可能指向任何一个已经复制过的节点,所有使用map保存已经生成过的节点,以方便后续获取
看了另一位大佬用了递归+hashmap 对各位大佬只能说:谢谢谢谢
class Solution {
Map<Node,Node> map=new HashMap<>();
public Node copyRandomList(Node head) {
if(head==null){
return null;
}
Node cur=head;
if(map.containsKey(head)){
cur=map.get(head);
return cur;
}else{
cur=new Node(head.val);
map.put(head,cur);
cur.next=copyRandomList(head.next);
cur.random=copyRandomList(head.random);
return cur;
}
}
}
class Solution {
public Node copyRandomList(Node head) {
if(head == null){
return null;
}
Map<Node, Node> map = new HashMap<>();
Node cur = head;
while(cur != null){
map.put(cur, new Node(cur.val));
cur = cur.next;
}
cur = head;
while(cur != null){
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
return map.get(head);
}
}
python3:
dic["键"]="值"
get('键','可以自己指定内容')
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head:
return
dic = {}
cur = head
while cur:
dic[cur] = Node(cur.val)
cur = cur.next
cur = head
while cur:
dic[cur].next = dic.get(cur.next)
dic[cur].random = dic.get(cur.random)
cur = cur.next
return dic[head]