/* public class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } } */ publicclassSolution{ public RandomListNode Clone(RandomListNode pHead){ // 特殊输入的检查 if (pHead == null) returnnull;
// 复制节点,放置在原节点的后面。例如:(a -> b -> c) --> (a -> a' -> b -> b' -> c -> c') RandomListNode n = pHead; while (n != null) { RandomListNode nCopy = new RandomListNode(n.label); nCopy.next = n.next; n.next = nCopy; n = nCopy.next;; }
// 复制 random 指针 n = pHead; while (n != null) { if (n.random != null) { n.next.random = n.random.next; } n = n.next.next; }