-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMiddleAndReverse.php
54 lines (47 loc) · 1.14 KB
/
MiddleAndReverse.php
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
<?php
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
class Solution {
/**
* @param ListNode $head
* @return NULL
*/
function reorderList($head) {
// find middle
$slow = $head;
$fast = $head->next;
while ($fast && $fast->next){
$slow = $slow->next;
$fast = $fast->next->next ;
}
// reverse second half
$second = $slow->next ;
$prev = $slow->next = null ;
while ($second){
$tmp = $second->next;
$second->next = $prev;
$prev = $second ;
$second = $tmp;
}
// merge two halfs
$first = $head;
$second = $prev;
while ($second){
$tmp1 = $first->next ;
$tmp2 = $second->next;
$first->next = $second ;
$second->next = $tmp1 ;
$first = $tmp1;
$second = $tmp2;
}
}
}