给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。
一刷ac
解题思路:用map存储节点和label,每次判断节点是否存在然后插入map,拷贝时把map对应节点的label取出来。
/**
* 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 {
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null) return null;
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
RandomListNode dummy = new RandomListNode(0);
RandomListNode point = dummy;
while(head != null){
if(!map.containsKey(head)){
map.put(head,new RandomListNode(head.label));
}
point.next = map.get(head);
if(head.random != null){
if(!map.containsKey(head.random)){
map.put(head.random,new RandomListNode(head.random.label));
}
point.next.random = map.get(head.random);
}
point = point.next;
head = head.next;
}
return dummy.next;
}
}