// Sort List
// 归并排序,时间复杂度O(nlogn),空间复杂度O(1)
package com.zhumq.lianxi;
public class SortListUseMergeSort {
public class ListNode{
private int val;
private ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public ListNode sortList(ListNode head) {
//节点为空或者只有一个节点
if (head == null || head.next == null)
return head;
//定位链表中点,使用快慢指针实现
final ListNode middle = findMiddle(head);
final ListNode head2 = middle.next;
// 断开
middle.next = null;
final ListNode l1 = sortList(head); // 前半段递归
final ListNode l2 = sortList(head2); // 后半段递归
//返回合并后的链表
return mergeTwoLists(l1, l2);
}
// 合并两个链表
private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
for (ListNode p = dummy; l1 != null || l2 != null; p = p.next) {
int val1 = l1 == null ? Integer.MAX_VALUE : l1.val;
int val2 = l2 == null ? Integer.MAX_VALUE : l2.val;
if (val1 <= val2) {
p.next = l1;
l1 = l1.next;
} else {
p.next = l2;
l2 = l2.next;
}
}
return dummy.next;
}
// 快慢指针找到中间节点
private static ListNode findMiddle(ListNode head) {
if (head == null) return null;
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
LeetCode------Sort List
最新推荐文章于 2025-02-12 09:13:32 发布