|
3 | 3 | import java.util.HashMap;
|
4 | 4 | import java.util.Map;
|
5 | 5 |
|
6 |
| -/**138. Copy List with Random Pointer |
| 6 | +/** |
| 7 | + * 138. Copy List with Random Pointer |
7 | 8 | *
|
8 | 9 | * A linked list is given such that each node contains an additional random
|
9 | 10 | * pointer which could point to any node in the list or null.
|
10 | 11 | * Return a deep copy of the list.
|
11 | 12 | * */
|
12 | 13 |
|
13 | 14 | public class _138 {
|
14 |
| - |
| 15 | + public static class Solution1 { |
15 | 16 | public RandomListNode copyRandomList(RandomListNode head) {
|
16 |
| - /**Key is the original nodes, value is the new nodes we're deep copying to.*/ |
17 |
| - Map<RandomListNode, RandomListNode> map = new HashMap(); |
18 |
| - RandomListNode node = head; |
19 |
| - |
20 |
| - //loop for the first time: copy the node themselves with only labels |
21 |
| - while (node != null) { |
22 |
| - map.put(node, new RandomListNode(node.label)); |
23 |
| - node = node.next; |
24 |
| - } |
25 |
| - |
26 |
| - //loop for the second time: copy random and next pointers |
27 |
| - node = head; |
28 |
| - while (node != null) { |
29 |
| - map.get(node).next = map.get(node.next); |
30 |
| - map.get(node).random = map.get(node.random); |
31 |
| - node = node.next; |
32 |
| - } |
33 |
| - |
34 |
| - return map.get(head); |
| 17 | + /**Key is the original nodes, value is the new nodes we're deep copying to.*/ |
| 18 | + Map<RandomListNode, RandomListNode> map = new HashMap(); |
| 19 | + RandomListNode node = head; |
| 20 | + |
| 21 | + //loop for the first time: copy the node themselves with only labels |
| 22 | + while (node != null) { |
| 23 | + map.put(node, new RandomListNode(node.label)); |
| 24 | + node = node.next; |
| 25 | + } |
| 26 | + |
| 27 | + //loop for the second time: copy random and next pointers |
| 28 | + node = head; |
| 29 | + while (node != null) { |
| 30 | + map.get(node).next = map.get(node.next); |
| 31 | + map.get(node).random = map.get(node.random); |
| 32 | + node = node.next; |
| 33 | + } |
| 34 | + |
| 35 | + return map.get(head); |
35 | 36 | }
|
36 | 37 |
|
37 | 38 | // Definition for singly-linked list with a random pointer.
|
38 | 39 | class RandomListNode {
|
39 |
| - int label; |
| 40 | + int label; |
40 | 41 |
|
41 |
| - RandomListNode next; |
42 |
| - RandomListNode random; |
| 42 | + RandomListNode next; |
| 43 | + RandomListNode random; |
43 | 44 |
|
44 |
| - RandomListNode(int x) { |
45 |
| - this.label = x; |
46 |
| - } |
| 45 | + RandomListNode(int x) { |
| 46 | + this.label = x; |
| 47 | + } |
47 | 48 | }
|
| 49 | + } |
48 | 50 | }
|
0 commit comments