##148. 排序链表
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) //空链表或者只有单个结点
return head;
//使用快慢指针寻找中间 结点
ListNode slow = head;
ListNode fast = head;
while (fast.next!=null && fast.next.next !=null){
slow = slow.next;
fast = fast.next.next;
}
ListNode ptr1 = slow.next;
slow.next = null;
ListNode start1 = sortList(head);
ListNode start2 = sortList(ptr1);
if (start1 == null) return start2;
if (start2 == null) return start1;
ListNode header = new ListNode(-1);
ListNode pre = header;
while (start1 != null && start2 != null) {
if (start1.val <= start2.val) {
pre.next = start1;
start1 = start1.next;
pre = pre.next;
} else {
pre.next = start2;
start2 = start2.next;
pre = pre.next;
}
}
if (start1 == null) {
pre.next = start2;
} else {
pre.next = start1;
}
return header.next;
}
}