File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed
src/Algorithms/0138.copy-list-with-random-pointer Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ // Definition for a Node.
3
+ class Node {
4
+ public $val;
5
+ public $next;
6
+ public $random;
7
+
8
+ @param Integer $val
9
+ @param Node $next
10
+ @param Node $random
11
+ function __construct($val, $next, $random) {
12
+ $this->val = $val;
13
+ $this->next = $next;
14
+ $this->random = $random;
15
+ }
16
+ }
17
+ */
18
+ class Solution {
19
+
20
+ /**
21
+ * @param Node $head
22
+ * @return Node
23
+ */
24
+ function copyRandomList($head) {
25
+ $iter = $head;
26
+ $next;
27
+
28
+ // First round: make copy of each node,
29
+ // and link them together side-by-side in a single list.
30
+ while ($iter != null) {
31
+ $next = $iter->next;
32
+
33
+ $copy = new Node($iter->val, null, null);
34
+ $iter->next = $copy;
35
+ $copy->next = $next;
36
+
37
+ $iter = $next;
38
+ }
39
+
40
+ // Second round: assign random pointers for the copy nodes.
41
+ $iter = $head;
42
+ while ($iter != null) {
43
+ if ($iter->random != null) {
44
+ $iter->next->random = $iter->random->next;
45
+ }
46
+ $iter = $iter->next->next;
47
+ }
48
+
49
+ // Third round: restore the original list, and extract the copy list.
50
+ $iter = $head;
51
+ $pseudoHead = new Node(0, null, null);
52
+ $copy;
53
+ $copyIter = $pseudoHead;
54
+
55
+ while ($iter != null) {
56
+ $next = $iter->next->next;
57
+
58
+ // extract the copy
59
+ $copy = $iter->next;
60
+ $copyIter->next = $copy;
61
+ $copyIter = $copy;
62
+
63
+ // restore the original list
64
+ $iter->next = $next;
65
+
66
+ $iter = $next;
67
+ }
68
+
69
+ return $pseudoHead->next;
70
+ }
71
+ }
You can’t perform that action at this time.
0 commit comments