题目:https://oj.leetcode.com/problems/sort-list/
ort a linked list in O(n log n) time using constant space complexity.
分析:常数空间且O(nlogn),单链表适合用归并排序,双向链表适合用快速排序
源码:Java版本
算法分析:归并排序,时间复杂度O(nlogn),空间复杂度O(1)
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if(head==null || head.next==null) {
return head;
}
ListNode slow=head,fast=head;
while(fast.next!=null && fast.next.next!=null) {
fast=fast.next.next;
slow=slow.next;
}
fast=slow;
slow=slow.next;
fast.next=null;
ListNode left=sortList(head);
ListNode right=sortList(slow);
return mergeTwoLists(left,right);
}
private ListNode mergeTwoLists(ListNode left,ListNode right) {
ListNode head=new ListNode(-1);
ListNode p=head;
while(left!=null && right!=null) {
if(left.val<right.val) {
p.next=left;
left=left.next;
}else {
p.next=right;
right=right.next;
}
p=p.next;
}
if(left!=null) {
p.next=left;
}
if(right!=null) {
p.next=right;
}
return head.next;
}
}