|
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 |
| -publicclassSolution { |
10 |
| -publicRandomListNodecopyRandomList(RandomListNodehead) { |
11 |
| -if (head ==null) { |
12 |
| -returnnull; |
13 |
| - } |
14 |
| - |
15 |
| -RandomListNodeans =newRandomListNode(head.label); |
16 |
| -RandomListNodecurr =ans; |
17 |
| - |
18 |
| -while (head !=null) { |
19 |
| -curr.next =head.next ==null ?null :newRandomListNode(head.next.label); |
20 |
| -curr.random =head.random ==null ?null :newRandomListNode(head.random.label); |
21 |
| - |
22 |
| -curr =curr.next; |
23 |
| -head =head.next; |
24 |
| - } |
25 |
| - |
26 |
| -returnans; |
| 1 | +/* |
| 2 | +// Definition for a Node. |
| 3 | +class Node { |
| 4 | + int val; |
| 5 | + Node next; |
| 6 | + Node random; |
| 7 | +
|
| 8 | + public Node(int val) { |
| 9 | + this.val = val; |
| 10 | + this.next = null; |
| 11 | + this.random = null; |
27 | 12 | }
|
28 | 13 | }
|
| 14 | +*/ |
| 15 | + |
| 16 | +classSolution { |
| 17 | +publicNodecopyRandomList(Nodehead) { |
| 18 | +Map<Node,Node>map =newHashMap<>(); |
| 19 | +Nodecurr =head; |
| 20 | +while (curr !=null) { |
| 21 | +map.put(curr,newNode(curr.val)); |
| 22 | +curr =curr.next; |
| 23 | + } |
| 24 | +curr =head; |
| 25 | +while (curr !=null) { |
| 26 | +Nodetemp =map.get(curr); |
| 27 | +temp.next =curr.next ==null ?null :map.get(curr.next); |
| 28 | +temp.random =curr.random ==null ?null :map.get(curr.random); |
| 29 | +curr =curr.next; |
| 30 | + } |
| 31 | +returnmap.get(head); |
| 32 | + } |
| 33 | +} |