Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit d80ba79

Browse files
refactor 138
1 parent dffda83 commit d80ba79

File tree

1 file changed

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

1 file changed

+36
-36
lines changed

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

Lines changed: 36 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -5,46 +5,46 @@
55

66
/**
77
* 138. Copy List with Random Pointer
8-
*
8+
*
99
* A linked list is given such that each node contains an additional random
1010
* pointer which could point to any node in the list or null.
1111
* Return a deep copy of the list.
12-
* */
12+
*/
1313

1414
public class _138 {
15-
public static class Solution1 {
16-
public Node copyRandomList(Node head) {
17-
/**Key is the original nodes, value is the new nodes we're deep copying to.*/
18-
Map<Node, Node> map = new HashMap();
19-
Node 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 Node(node.val));
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);
15+
public static class Solution1 {
16+
public Node copyRandomList(Node head) {
17+
/**Key is the original nodes, value is the new nodes we're deep copying to.*/
18+
Map<Node, Node> map = new HashMap();
19+
Node 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 Node(node.val));
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);
36+
}
37+
38+
// Definition for singly-linked list with a random pointer.
39+
class Node {
40+
int val;
41+
42+
Node next;
43+
Node random;
44+
45+
Node(int x) {
46+
this.val = x;
47+
}
48+
}
3649
}
37-
38-
// Definition for singly-linked list with a random pointer.
39-
class Node {
40-
int val;
41-
42-
Node next;
43-
Node random;
44-
45-
Node(int x) {
46-
this.val = x;
47-
}
48-
}
49-
}
5050
}

0 commit comments

Comments
 (0)