给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
思路: 归并
/*** Definition for a singly-linked list.* class ListNode {* public $val = 0;* public $next = null;* function __construct($val) { $this->val = $val; }* }*/class Solution {/*** @param ListNode $head* @return ListNode*/function sortList($head){if($head->next == null){return $head;}$fast = $head->next;$slow = $head;while($fast !=null && $fast->next != null){$fast = $fast->next->next;$slow = $slow->next;}$tail = $slow->next;$slow->next = null;$head = $this->sortList($head);$tail = $this->sortList($tail);return $this->merge($head,$tail);}function merge($t1,$t2){$node = new ListNode(-1);$cur = $node;while($t1 != null && $t2 !=null){if($t1->val > $t2->val){$cur->next = $t2;$t2 = $t2->next;}else{$cur->next = $t1;$t1 = $t1->next;}$cur = $cur->next;}$cur->next = ($t1 == null) ? $t2 : $t1;return $node->next;}}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
