Copy List with Random Pointers
复制带随机指针的链表
思路1:使用哈希表,需要消耗O(N)的额外空间。
1 public class Solution { 2 /** 3 * @param head: The head of linked list with a random pointer. 4 * @return: A new head of a deep copy of the list. 5 */ 6 public RandomListNode copyRandomList(RandomListNode head) { 7 // write your code here 8 9 Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>(); 10 RandomListNode cur = head; 11 RandomListNode copyDummy = new RandomListNode(0); 12 RandomListNode copyCur = copyDummy; 13 14 while (cur != null) { 15 copyCur.next = new RandomListNode(cur.label); 16 copyCur = copyCur.next; 17 map.put(cur, copyCur); 18 cur = cur.next; 19 } 20 21 cur = head; 22 while (cur != null) { 23 copyCur = map.get(cur); 24 copyCur.random = map.get(cur.random); 25 cur = cur.next; 26 } 27 return copyDummy.next; 28 } 29 }