138. Copy List with Random Pointer
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.
難度:medium
題目:給定一連結串列其每個結點包含一隨機指標可以指向任意一結點或是為空。
思路:hash map
Runtime: 2 ms, faster than 72.52% of Java online submissions for Copy List with Random Pointer.
Memory Usage: 38.5 MB, less than 100.00% of Java online submissions for Copy List with Random Pointer.
/** * 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> mrr = new HashMap<>(); RandomListNode ptr = head; while (ptr != null) { mrr.put(ptr, new RandomListNode(ptr.label)); ptr = ptr.next; } ptr = head; while (ptr != null) { RandomListNode node = mrr.get(ptr); node.next = mrr.get(ptr.next); node.random = mrr.get(ptr.random); ptr = ptr.next; } return mrr.get(head); } }