Copy List with Random Pointer
不明白为啥标记为Hard。 如果不用哈希表,实现起来却是挺麻烦。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
public RandomListNode (RandomListNode head) { if (head == null) return head; HashMap<RandomListNode, RandomListNode> map = new HashMap<>(); RandomListNode ptr = head; map.put(ptr, new RandomListNode(ptr.label)); while (ptr != null) { if(ptr.next != null) { map.put(ptr.next, new RandomListNode(ptr.next.label)); map.get(ptr).next = map.get(ptr.next); } ptr = ptr.next; } ptr = head; while (ptr != null) { RandomListNode rand = ptr.random; if (rand != null) map.get(ptr).random = map.get(rand); ptr = ptr.next; } return map.get(head); }
|
近期评论