|
| 1 | +/** |
| 2 | + * 138. Copy List with Random Pointer |
| 3 | + * https://leetcode.com/problems/copy-list-with-random-pointer/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A linked list of length n is given such that each node contains an additional random pointer, |
| 7 | + * which could point to any node in the list, or null. |
| 8 | + * |
| 9 | + * Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, |
| 10 | + * where each new node has its value set to the value of its corresponding original node. Both |
| 11 | + * the next and random pointer of the new nodes should point to new nodes in the copied list such |
| 12 | + * that the pointers in the original list and copied list represent the same list state. None of |
| 13 | + * the pointers in the new list should point to nodes in the original list. |
| 14 | + * |
| 15 | + * For example, if there are two nodes X and Y in the original list, where X.random --> Y, then |
| 16 | + * for the corresponding two nodes x and y in the copied list, x.random --> y. |
| 17 | + * |
| 18 | + * Return the head of the copied linked list. |
| 19 | + * |
| 20 | + * The linked list is represented in the input/output as a list of n nodes. Each node is |
| 21 | + * represented as a pair of [val, random_index] where: |
| 22 | + * - val: an integer representing Node.val |
| 23 | + * - random_index: the index of the node (range from 0 to n-1) that the random pointer points |
| 24 | + * to, or null if it does not point to any node. |
| 25 | + * |
| 26 | + * Your code will only be given the head of the original linked list. |
| 27 | + */ |
| 28 | + |
| 29 | +/** |
| 30 | + * // Definition for a Node. |
| 31 | + * function Node(val, next, random) { |
| 32 | + * this.val = val; |
| 33 | + * this.next = next; |
| 34 | + * this.random = random; |
| 35 | + * }; |
| 36 | + */ |
| 37 | + |
| 38 | +/** |
| 39 | + * @param {Node} head |
| 40 | + * @return {Node} |
| 41 | + */ |
| 42 | +var copyRandomList = function(head) { |
| 43 | + const map = new Map(); |
| 44 | + |
| 45 | + function copy(reference) { |
| 46 | + if (reference === null) return null; |
| 47 | + const instance = map.get(reference); |
| 48 | + if (instance) { |
| 49 | + return instance; |
| 50 | + } |
| 51 | + |
| 52 | + const node = new Node(reference.val); |
| 53 | + map.set(reference, node); |
| 54 | + node.next = copy(reference.next); |
| 55 | + node.random = copy(reference.random); |
| 56 | + |
| 57 | + return node; |
| 58 | + } |
| 59 | + |
| 60 | + return copy(head); |
| 61 | +}; |
0 commit comments