题目:
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.
不要想的太复杂了。直接用个hashMap存储原始结点和copy的结点的对应关系。
先把结点整个从头到尾进行复制。然后从头到尾复制它的random
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
Map<RandomListNode,RandomListNode> map = new HashMap<>();
RandomListNode p = head;
RandomListNode dummy = new RandomListNode(0);
RandomListNode q = dummy;
while(p!=null) {
q.next = new RandomListNode(p.label);
map.put(p,q.next);
p = p.next;
q = q.next;
}
p = head;
q = dummy.next;
while(p!=null) {
q.random = map.get(p.random);
p = p.next;
q = q.next;
}
return dummy.next;
}
}