|
| 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 ListNode |
| 14 | + */ |
| 15 | + function sortList($head) { |
| 16 | + if ($head == null || $head->next == null) |
| 17 | + return $head; |
| 18 | + $slow = $head; |
| 19 | + $fast = $head; |
| 20 | + $pre = $slow; |
| 21 | + while($fast != null && $fast->next != null) { |
| 22 | + $pre = $slow; |
| 23 | + $slow = $slow->next; |
| 24 | + $fast = $fast->next->next; |
| 25 | + } |
| 26 | + $pre->next = null; |
| 27 | + $first = self::sortList($head); |
| 28 | + $second = self::sortList($slow); |
| 29 | + $res = new ListNode(1); |
| 30 | + $cur = $res; |
| 31 | + while ($first != null || $second != null) { |
| 32 | + if ($first == null) { |
| 33 | + $cur->next= $second; |
| 34 | + break; |
| 35 | + } else if ($second == null) { |
| 36 | + $cur->next = $first; |
| 37 | + break; |
| 38 | + } else if ($first->val <= $second->val) { |
| 39 | + $cur->next = $first; |
| 40 | + $first = $first->next; |
| 41 | + $cur = $cur->next; |
| 42 | + } else { |
| 43 | + $cur->next = $second; |
| 44 | + $second = $second->next; |
| 45 | + $cur = $cur->next; |
| 46 | + } |
| 47 | + } |
| 48 | + return $res->next; |
| 49 | + } |
| 50 | +} |
0 commit comments