Problem: 148. 排序链表
👩🏫 参考文章来源:https://www.toymoban.com/news/detail-824870.html
💖 归并排序(递归)
⏰ 时间复杂度:
O
(
n
)
O(n)
O(n)
🌎 空间复杂度:
O
(
n
)
O(n)
O(n)
文章来源地址https://www.toymoban.com/news/detail-824870.html
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head)
{
if (head == null || head.next == null)
return head;
ListNode fast = head.next;
ListNode slow = head;
while (fast != null && fast.next != null)
{
slow = slow.next;
fast = fast.next.next;
}
ListNode second = slow.next;
slow.next = null;// 断开前后两段的联系
ListNode left = sortList(head);
ListNode right = sortList(second);
ListNode h = new ListNode(0);
ListNode dummy = h;
while (left != null && right != null)
{
if (left.val < right.val)
{
h.next = left;
left = left.next;
} else
{
h.next = right;
right = right.next;
}
h = h.next;
}
h.next = left != null ? left : right;
return dummy.next;
}
}
到了这里,关于力扣hot100 排序链表 归并排序 递归的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!