
维护一个map里面有一个映射关系,新链表和老链表节点的一一映射的关系
import java.util.*;
public class Solution {
public RandomListNode Clone(RandomListNode pHead) {
if(pHead == null) {
return null;
}
HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode temp = pHead;
while(temp != null) {
map.put(temp, new RandomListNode(temp.label));
temp = temp.next;
}
RandomListNode target = map.get(pHead);
RandomListNode p = map.get(pHead);
while(pHead != null) {
target.next = map.get(pHead.next);
target.random = map.get(pHead.random);
target = target.next;
pHead = pHead.next;
}
return p;
}
}