/**
* 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 ListNode
*/
function sortList($head) {
if (is_null($head) || is_null($head->next)) {
return $head;
}
return $this->sort($head, null);
}
/**
* 注:这个链表是包含head, 不包含tail的左闭右开
* @param $head
* @param $tail
*/
function sort($head, $tail) {
if (is_null($head)) {
return $head;
}
// 这个链表是包含head, 不包含tail的左闭右开
if ($head->next == $tail) {
$head->next = null;
return $head;
}
$fast = $head;
$slow = $head;
while ($fast != $tail && $fast->next != $tail) {
$fast = $fast->next->next;
$slow = $slow->next;
}
return $this->mergeTwoList($this->sort($head, $slow), $this->sort($slow, $tail));
}
function mergeTwoList($node1, $node2) {
if (is_null($node1)) {
return $node2;
}
if (is_null($node2)) {
return $node1;
}
$head = null;
if ($node1->val < $node2->val) {
$head = $node1;
$node1->next = $this->mergeTwoList($node1->next, $node2);
} else {
$head = $node2;
$node2->next = $this->mergeTwoList($node1, $node2->next);
}
return $head;
}
}
排序链表【php版】
最新推荐文章于 2021-08-10 18:01:12 发布