思路如下:
深拷贝是指源对象与拷贝对象互相独立,其中任何一个对象的改动都不会对另外一个对象造成影响。题目要求深拷贝,即重新写一个一模一样的head出来。我们可以考虑采用HashMap来实现深拷贝。
先建立各结点,然后再将各结点连接起来。
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
Map<Node,Node> map=new HashMap<>();
public Node copyRandomList(Node head) {
if(head==null){
return null;
}
//建立各结点,与已知结点构成键值对
Node cur=head;
while(cur!=null){
map.put(cur,new Node(cur.val));
cur=cur.next;
}
//连接各结点,对map中的node值进行操作
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);
}
}
原题地址:
138. 复制带随机指针的链表