思路:
在原链表每个节点后复制一个相同的节点。但是random为null。
然后遍历进行链表指向。
/*
// Definition for a Node.
class Node {
public int val;
public Node next;
public Node random;
public Node() {}
public Node(int _val,Node _next,Node _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Solution {
public Node copyRandomList(Node head) {
if(head==null)
return head;
Node h = head;
//复制next
while(h!=null){
Node h_clone = new Node(h.val,null,null);
h_clone.next = h.next;
h.next = h_clone;
h = h.next.next;
}
h = head;
//复制random
while(h!=null){
if(h.random!=null){
h.next.random = h.random.next;
}
h = h.next.next;
}
Node cloneH =head.next;
h=head;
Node temp ;
//断开链表
while(h.next!=null){
temp = h.next;
h.next=h.next.next;
h =temp;
}
return cloneH;
}
}