-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomListNode.java
More file actions
64 lines (53 loc) · 1.11 KB
/
RandomListNode.java
File metadata and controls
64 lines (53 loc) · 1.11 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.HashMap;
import java.util.Map;
// Definition for singly-linked list with a random pointer.
class RandomListNode
{
int label;
RandomListNode next, random;
RandomListNode( int x )
{
this.label = x;
}
RandomListNode( int[] a )
{
Map<Integer, RandomListNode> _map = new HashMap<>();
// assuming all int values are distinct
RandomListNode tmp = this;
tmp.label = a[0];
_map.put( a[0], tmp );
for ( int i = 2; i < a.length; i += 2 )
{
RandomListNode k = new RandomListNode( a[i] );
tmp.next = k;
_map.put( a[i], k );
tmp = tmp.next; // puts all values into list
}
tmp = this;
for ( int i = 1; i < a.length; i += 2 )
{
tmp.random = _map.get( a[i] );
tmp = tmp.next;
}
}
public void print()
{
RandomListNode t = this;
System.out.print( "Listnode: " );
while ( t != null )
{
System.out.print( "->" + t );
t = t.next;
}
System.out.print( "->NULL" );
t = this;
System.out.print( "\nRandomNode: " );
while ( t != null )
{
System.out.print( "->" + t.random );
t = t.next;
}
System.out.print( "->NULL" );
System.out.println();
}
};