forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
138_copyRandomList.java
32 lines (29 loc) · 961 Bytes
/
138_copyRandomList.java
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
31
32
/**
* 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 run = head;
while(run!=null){
RandomListNode newRun = new RandomListNode(run.label);
newRun.next = run;
map.put(run, newRun);
run = run.next;
}
run = head;
while(run!=null){
RandomListNode newRun = map.get(run);
newRun.random = map.get(newRun.next.random);
newRun.next = map.get(newRun.next.next);
run = run.next;
}
return map.get(head);
}
}