给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。

    进阶:

    你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?

    示例 1:
    image.png

    输入:head = [4,2,1,3]
    输出:[1,2,3,4]
    示例 2:
    image.png

    输入:head = [-1,5,3,4,0]
    输出:[-1,0,3,4,5]

    思路: 归并

    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. * @param ListNode $head
    12. * @return ListNode
    13. */
    14. function sortList($head){
    15. if($head->next == null){
    16. return $head;
    17. }
    18. $fast = $head->next;
    19. $slow = $head;
    20. while($fast !=null && $fast->next != null){
    21. $fast = $fast->next->next;
    22. $slow = $slow->next;
    23. }
    24. $tail = $slow->next;
    25. $slow->next = null;
    26. $head = $this->sortList($head);
    27. $tail = $this->sortList($tail);
    28. return $this->merge($head,$tail);
    29. }
    30. function merge($t1,$t2){
    31. $node = new ListNode(-1);
    32. $cur = $node;
    33. while($t1 != null && $t2 !=null){
    34. if($t1->val > $t2->val){
    35. $cur->next = $t2;
    36. $t2 = $t2->next;
    37. }else{
    38. $cur->next = $t1;
    39. $t1 = $t1->next;
    40. }
    41. $cur = $cur->next;
    42. }
    43. $cur->next = ($t1 == null) ? $t2 : $t1;
    44. return $node->next;
    45. }
    46. }

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/sort-list
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。