[LeetCode] 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.
Thought process:
The problem is that, as we iterate through the list, current.random may not have been created. One solution is to iterate through the list twice and use a hashmap.
- First iteration: copy nodes' values, next pointers, and map old node -> new node.
- Second iteration: copy random pointers.
Solution 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | /** * 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) { if (head == null) { return null; } RandomListNode headCopy = new RandomListNode(head.label); RandomListNode curr1 = head; RandomListNode curr2 = headCopy; Map<RandomListNode, RandomListNode> map = new HashMap<>(); map.put(curr1, curr2); while (curr1.next != null) { RandomListNode copy = new RandomListNode(curr1.next.label); curr2.next = copy; curr1 = curr1.next; curr2 = curr2.next; map.put(curr1, curr2); } curr1 = head; while (curr1 != null) { map.get(curr1).random = map.get(curr1.random); curr1 = curr1.next; } return headCopy; } } |
Time complexity: O(n).
Can we solve this without using a hashmap?
Yes. The trick is to put a node's copy at node.next, and split the list afterwards.
Solution 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | /** * 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) { if (head == null) { return null; } RandomListNode current = head; while (current != null) { RandomListNode next = current.next; current.next = new RandomListNode(current.label); current.next.next = next; current = next; } current = head; while (current != null) { if (current.random != null) { current.next.random = current.random.next; } current = current.next.next; } current = head; RandomListNode headCopy = current.next; RandomListNode currCopy = headCopy; while (current != null) { current.next = current.next.next; if (currCopy.next != null) { currCopy.next = currCopy.next.next; } current = current.next; currCopy = currCopy.next; } return headCopy; } } |
Time complexity: O(n).
Comments
Post a Comment