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.
题目含义:深度拷贝一个列表,列表中的节点包含random成员
思路:以每一个节点为key,构造一个实例作为value维护在map中,然后从head开始依次连接各节点
1 public RandomListNode copyRandomList(RandomListNode head) { 2 if (head == null) return null; 3 Map<RandomListNode, RandomListNode> map = new HashMap<>(); 4 RandomListNode node = head; 5 while (node != null) { 6 map.put(node, new RandomListNode(node.label)); 7 node = node.next; 8 } 9 node = head; 10 while (node != null) { 11 map.get(node).next = map.get(node.next); 12 map.get(node).random = map.get(node.random); 13 node = node.next; 14 } 15 return map.get(head); 16 }