Skip to content

Commit cb52ce2

Browse files
committed
copyListWithRandomPointer
1 parent e6a977f commit cb52ce2

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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) { return null; }
12+
13+
HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
14+
LinkedList<RandomListNode> queue = new LinkedList<RandomListNode>();
15+
queue.add(head);
16+
RandomListNode newHead = new RandomListNode(head.label);
17+
map.put(head, newHead);
18+
while (queue.size() > 0) {
19+
RandomListNode node = queue.poll();
20+
RandomListNode newNode = map.get(node);
21+
22+
if (node.next != null) {
23+
if (!map.containsKey(node.next)) {
24+
RandomListNode nextNode = new RandomListNode(node.next.label);
25+
map.put(node.next, nextNode);
26+
}
27+
queue.add(node.next);
28+
newNode.next = map.get(node.next);
29+
}
30+
if (node.random != null) {
31+
if (!map.containsKey(node.random)) {
32+
RandomListNode randNode = new RandomListNode(node.random.label);
33+
map.put(node.random, randNode);
34+
}
35+
newNode.random = map.get(node.random);
36+
}
37+
}
38+
return newHead;
39+
}
40+
}

0 commit comments

Comments
 (0)