Skip to content

Commit 121ca50

Browse files
authored
Refactored Copy List with Random Pointer.java
1 parent d54d295 commit 121ca50

File tree

1 file changed

+31
-26
lines changed

1 file changed

+31
-26
lines changed
Lines changed: 31 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,33 @@
1-
/**
2-
* Definition for singly-linked list with a random pointer.
3-
* class RandomListNode {
4-
* int label;
5-
* RandomListNode next, random;
6-
* RandomListNode(int x) { this.label = x; }
7-
* };
8-
*/
9-
public class Solution {
10-
public RandomListNode copyRandomList(RandomListNode head) {
11-
if (head == null) {
12-
return null;
13-
}
14-
15-
RandomListNode ans = new RandomListNode(head.label);
16-
RandomListNode curr = ans;
17-
18-
while (head != null) {
19-
curr.next = head.next == null ? null : new RandomListNode(head.next.label);
20-
curr.random = head.random == null ? null : new RandomListNode(head.random.label);
21-
22-
curr = curr.next;
23-
head = head.next;
24-
}
25-
26-
return ans;
1+
/*
2+
// Definition for a Node.
3+
class Node {
4+
int val;
5+
Node next;
6+
Node random;
7+
8+
public Node(int val) {
9+
this.val = val;
10+
this.next = null;
11+
this.random = null;
2712
}
2813
}
14+
*/
15+
16+
class Solution {
17+
public Node copyRandomList(Node head) {
18+
Map<Node, Node> map = new HashMap<>();
19+
Node curr = head;
20+
while (curr != null) {
21+
map.put(curr, new Node(curr.val));
22+
curr = curr.next;
23+
}
24+
curr = head;
25+
while (curr != null) {
26+
Node temp = map.get(curr);
27+
temp.next = curr.next == null ? null : map.get(curr.next);
28+
temp.random = curr.random == null ? null : map.get(curr.random);
29+
curr = curr.next;
30+
}
31+
return map.get(head);
32+
}
33+
}

0 commit comments

Comments
 (0)