|
| 1 | +/** |
| 2 | + * Definition for singly-linked list with a random pointer. |
| 3 | + * function RandomListNode(label) { |
| 4 | + * this.label = label; |
| 5 | + * this.next = this.random = null; |
| 6 | + * } |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * @param {RandomListNode} head |
| 11 | + * @return {RandomListNode} |
| 12 | + */ |
| 13 | +const copyRandomList = function(head) { |
| 14 | + if (head == null) { |
| 15 | + return null; |
| 16 | + } |
| 17 | + |
| 18 | + // Creating a new weaved list of original and copied nodes. |
| 19 | + let ptr = head; |
| 20 | + while (ptr != null) { |
| 21 | + |
| 22 | + // Cloned node |
| 23 | + const newNode = new RandomListNode(ptr.label); |
| 24 | + |
| 25 | + // Inserting the cloned node just next to the original node. |
| 26 | + // If A->B->C is the original linked list, |
| 27 | + // Linked list after weaving cloned nodes would be A->A'->B->B'->C->C' |
| 28 | + newNode.next = ptr.next; |
| 29 | + ptr.next = newNode; |
| 30 | + ptr = newNode.next; |
| 31 | + } |
| 32 | + |
| 33 | + ptr = head; |
| 34 | + |
| 35 | + // Now link the random pointers of the new nodes created. |
| 36 | + // Iterate the newly created list and use the original nodes' random pointers, |
| 37 | + // to assign references to random pointers for cloned nodes. |
| 38 | + while (ptr != null) { |
| 39 | + ptr.next.random = (ptr.random != null) ? ptr.random.next : null; |
| 40 | + ptr = ptr.next.next; |
| 41 | + } |
| 42 | + |
| 43 | + // Unweave the linked list to get back the original linked list and the cloned list. |
| 44 | + // i.e. A->A'->B->B'->C->C' would be broken to A->B->C and A'->B'->C' |
| 45 | + let ptr_old_list = head; // A->B->C |
| 46 | + let ptr_new_list = head.next; // A'->B'->C' |
| 47 | + let head_old = head.next; |
| 48 | + while (ptr_old_list != null) { |
| 49 | + ptr_old_list.next = ptr_old_list.next.next; |
| 50 | + ptr_new_list.next = (ptr_new_list.next != null) ? ptr_new_list.next.next : null; |
| 51 | + ptr_old_list = ptr_old_list.next; |
| 52 | + ptr_new_list = ptr_new_list.next; |
| 53 | + } |
| 54 | + return head_old; |
| 55 | +}; |
0 commit comments