原题地址:https://leetcode-cn.com/problems/sort-list/
题目描述:
在 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 lo = head, mid = head, hi = head;
while(hi.next != null && hi.next.next != null)
{
mid = mid.next;
hi = hi.next.next;
}
hi = mid.next;
mid.next = null;
ListNode i = sortList(lo);
ListNode j = sortList(hi);
ListNode n_head = new ListNode(-1);
ListNode k = n_head;
while(i != null && j != null)
{
if(i.val < j.val)
{
k.next = i;
i = i.next;
}
else
{
k.next = j;
j = j.next;
}
k = k.next;
}
if(i == null)
k.next = j;
if(j == null)
k.next = i;
return n_head.next;
}
}