A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
code
注意某个节点没有next,但是有random的情况
/**
* Definition for singly-linked list with a random pointer.
* public class RandomListNode {
* public int label;
* public RandomListNode next, random;
* public RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode CopyRandomList(RandomListNode head) {
if(head==null) return head;
RandomListNode clonehead = new RandomListNode(head.label);
if(head.next!=null)
clonehead.next = new RandomListNode(head.next.label);
if(head.random!=null)
clonehead.random = new RandomListNode(head.random.label);
RandomListNode next = CopyRandomList(head.next);
var cur = clonehead.next;
if(next!=null){
cur.next = next.next;
cur.random = next.random;
}
return clonehead;
}
}