/**
* 148. 排序链表
* @author wsq
* @date 2020/11/21
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
示例1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
链接:https://leetcode-cn.com/problems/sort-list
*/
package com.wsq.linkedllisk;
public class MergeSortList {
/**
* 自顶向下归并排序
* 借用递归的方式实现,该算法时间复杂度为O(nlog(n)),由于采用的是递归方式实现,因此空间复杂度O(logn)
* @param head
* @return
*/
public ListNode sortList(ListNode head) {
return sortList(head, null);
}
private ListNode sortList(ListNode head, Object tail) {
if(head == null) {
return head;
}
if(head.next == tail) {
head.next = null;
return head;
}
// 采用快慢指针获取链表的中点,这个方式可以学一下,以后可以用到
ListNode slow = head;
ListNode fast = head;
while(fast != tail) {
slow = slow.next;
fast = fast.next;
if(fast != tail) {
fast = fast.next;
}
}
ListNode mid = slow;
ListNode leftList = sortList(head, mid);
ListNode rightList = sortList(mid, tail);
return merge(leftList, rightList);
}
private ListNode merge(ListNode leftList, ListNode rightList) {
// 合并两个链表
ListNode head = new ListNode(0);
ListNode tmp1 = leftList;
ListNode tmp2 = rightList;
ListNode node = head;
while(tmp1 != null && tmp2 != null) {
if(tmp1.val <= tmp2.val) {
node.next = tmp1;
tmp1 = tmp1.next;
}else {
node.next = tmp2;
tmp2 = tmp2.next;
}
node = node.next;
}
if(tmp1 != null) {
node.next = tmp1;
}else {
node.next = tmp2;
}
return head.next;
}
}
148. 排序链表(归并排序,递归实现)
最新推荐文章于 2022-06-17 23:38:59 发布