-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy random pointer.java
More file actions
30 lines (28 loc) · 931 Bytes
/
copy random pointer.java
File metadata and controls
30 lines (28 loc) · 931 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null) return null;
HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>();
RandomListNode node = head;
// create new nodes
while(node != null){
map.put(node, new RandomListNode(node.label));
node = node.next;
}
//copy next and random reference
node = head;
while(node != null){
map.get(node).next = map.get(node.next); //ÐÂ1 ££¾Ð£²
map.get(node).random = map.get(node.random);
node = node.next;
}
return map.get(head);
}
}