Skip to content

Commit 2bffa1c

Browse files
authored
Add file Copy_list_with_random_pointer.java
1 parent ae717a3 commit 2bffa1c

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Copy_list_with_random_pointer.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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 Copy_list_with_random_pointer {
10+
public RandomListNode copyRandomList(RandomListNode head) {
11+
if (head == null) {
12+
return null;
13+
}
14+
Map<RandomListNode, RandomListNode> map = new HashMap<>();
15+
for (RandomListNode n = head; n != null; n = n.next) {
16+
map.put(n, new RandomListNode(n.label));
17+
}
18+
for (RandomListNode n = head; n != null; n = n.next) {
19+
map.get(n).next = map.get(n.next);
20+
map.get(n).random = map.get(n.random);
21+
}
22+
return map.get(head);
23+
}
24+
}

0 commit comments

Comments
 (0)