File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed
src/Algorithms/0143.reorder-list Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Definition for a singly-linked list.
3+ * class ListNode {
4+ * public $val = 0;
5+ * public $next = null;
6+ * function __construct($val) { $this->val = $val; }
7+ * }
8+ */
9+ class Solution {
10+
11+ /**
12+ * @param ListNode $head
13+ * @return NULL
14+ */
15+ function reorderList ($head ) {
16+ if ($head == null ) return ;
17+ $slow = $head ;
18+ $fast = $head ;
19+
20+ while ($fast != null && $fast -> next != null ){
21+ $fast = $fast -> next -> next ;
22+ $slow = $slow -> next ;
23+ }
24+
25+ $next = null ;
26+ $curr = $slow ;
27+ $prev = null ;
28+ while ($curr != null ){
29+ $next = $curr -> next ;
30+ $curr -> next = $prev ;
31+ $prev = $curr ;
32+ $curr = $next ;
33+ }
34+
35+ $temp ;
36+ while ($prev != null && $head -> next != null ){
37+ $temp = $head -> next ;
38+ $head -> next = $prev ;
39+ $head = $temp ;
40+
41+ $temp = $prev -> next ;
42+ $prev -> next = $head ;
43+ $prev = $temp ;
44+ }
45+ $head -> next = null ;
46+ }
47+ }
You can’t perform that action at this time.
0 commit comments