Skip to content

Commit 9fb6b38

Browse files
refactor 138
1 parent bec80bc commit 9fb6b38

File tree

1 file changed

+29
-27
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+29
-27
lines changed

src/main/java/com/fishercoder/solutions/_138.java

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,46 +3,48 @@
33
import java.util.HashMap;
44
import java.util.Map;
55

6-
/**138. Copy List with Random Pointer
6+
/**
7+
* 138. Copy List with Random Pointer
78
*
89
* A linked list is given such that each node contains an additional random
910
* pointer which could point to any node in the list or null.
1011
* Return a deep copy of the list.
1112
* */
1213

1314
public class _138 {
14-
15+
public static class Solution1 {
1516
public RandomListNode copyRandomList(RandomListNode head) {
16-
/**Key is the original nodes, value is the new nodes we're deep copying to.*/
17-
Map<RandomListNode, RandomListNode> map = new HashMap();
18-
RandomListNode node = head;
19-
20-
//loop for the first time: copy the node themselves with only labels
21-
while (node != null) {
22-
map.put(node, new RandomListNode(node.label));
23-
node = node.next;
24-
}
25-
26-
//loop for the second time: copy random and next pointers
27-
node = head;
28-
while (node != null) {
29-
map.get(node).next = map.get(node.next);
30-
map.get(node).random = map.get(node.random);
31-
node = node.next;
32-
}
33-
34-
return map.get(head);
17+
/**Key is the original nodes, value is the new nodes we're deep copying to.*/
18+
Map<RandomListNode, RandomListNode> map = new HashMap();
19+
RandomListNode node = head;
20+
21+
//loop for the first time: copy the node themselves with only labels
22+
while (node != null) {
23+
map.put(node, new RandomListNode(node.label));
24+
node = node.next;
25+
}
26+
27+
//loop for the second time: copy random and next pointers
28+
node = head;
29+
while (node != null) {
30+
map.get(node).next = map.get(node.next);
31+
map.get(node).random = map.get(node.random);
32+
node = node.next;
33+
}
34+
35+
return map.get(head);
3536
}
3637

3738
// Definition for singly-linked list with a random pointer.
3839
class RandomListNode {
39-
int label;
40+
int label;
4041

41-
RandomListNode next;
42-
RandomListNode random;
42+
RandomListNode next;
43+
RandomListNode random;
4344

44-
RandomListNode(int x) {
45-
this.label = x;
46-
}
45+
RandomListNode(int x) {
46+
this.label = x;
47+
}
4748
}
49+
}
4850
}

0 commit comments

Comments
 (0)