-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Deep copy linked list with random pointer.java
- Loading branch information
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
/* | ||
Each of the nodes in the linked list has another pointer pointing to a random node in the list or null. | ||
Make a deep copy of the original list. | ||
time = O(n) | ||
space = O(n) hashmap to avoid duplication | ||
*/ | ||
|
||
/** | ||
* class ListNode { | ||
* public int value; | ||
* public ListNode next; | ||
* public ListNode(int value) { | ||
* this.value = value; | ||
* next = null; | ||
* } | ||
* } | ||
*/ | ||
public class Solution { | ||
public RandomListNode copy(RandomListNode head) { | ||
// Write your solution here | ||
if (head == null) { | ||
return head; | ||
} | ||
RandomListNode dummy = new RandomListNode(0); | ||
RandomListNode cur = dummy; | ||
Map<RandomListNode, RandomListNode> map = new HashMap<>(); | ||
while (head != null) { | ||
if (!map.containsKey(head)) { | ||
map.put(head, new RandomListNode(head.value)); | ||
} | ||
cur.next = map.get(head); | ||
if (head.random != null) { | ||
if (!map.containsKey(head.random)) { | ||
map.put(head.random, new RandomListNode(head.random.value)); | ||
} | ||
cur.next.random = map.get(head.random); | ||
} | ||
head = head.next; | ||
cur = cur.next; | ||
} | ||
return dummy.next; | ||
} | ||
} |