思路:
- 复制节点的 val ,next 和 random 暂时为空
- 将源节点和克隆节点形成映射存放在一个 HashMap 中
public class CopyList {
public Node copyRandomList(Node head) {
if(head==null) {
return null;
}
Node p=head;
Map<Node, Node> map = new HashMap<Node, Node>();
while (p!=null) {
map.put(p, new Node(p.val));
p=p.next;
}
p=head;
while (p!=null) {
map.get(p).next=map.get(p.next);
map.get(p).random=map.get(p.random);
p=p.next;
}
return map.get(head);
}
}
class Node {
int val;
Node next;
Node random;
public Node(int x) {
val = x;
next = null;
random = null;
}
}
方法二:
public Node copyRandomList(Node head) {
if (head == null) return null;
//克隆源节点
Node p = head;
while (p != null) {
Node temp = p.next;
p.next = new Node(p.val);
p.next.next = temp;
p = temp;
}
//给克隆节点的 random 赋值
p = head;
while (p != null) {
if (p.random != null) p.next.random = p.random.next;
p = p.next.next;
}
//拆分
p= head;
Node cloneHead = p.next;
Node cloneP = cloneHead;
while (cloneP.next != null) {
//原链表
p.next = p.next.next;
p=p.next;
//克隆链表
cloneP.next = cloneP.next.next;
cloneP = cloneP.next;
}
//最后不要忘了给原链表收尾
p.next = null;
return cloneHead;
}