-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathinterviewbit-hashing-copy-list.java
33 lines (33 loc) · 1.14 KB
/
interviewbit-hashing-copy-list.java
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
/**
* 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) {
HashMap<Integer, RandomListNode> nodes = new HashMap<Integer, RandomListNode>();
RandomListNode copyHead = new RandomListNode(head.label);
nodes.put(copyHead.label, copyHead);
RandomListNode current = head;
RandomListNode currentCopy = copyHead;
while (current.next != null) {
currentCopy.next = new RandomListNode(current.next.label);
currentCopy = currentCopy.next;
nodes.put(currentCopy.label, currentCopy);
current = current.next;
}
current = head;
currentCopy = copyHead;
while (current != null) {
if (current.random != null) {
currentCopy.random = nodes.get(current.random.label);
}
current = current.next;
currentCopy = currentCopy.next;
}
return copyHead;
}
}