題目描述
在O(n log n)的時間內使用常數級空間複雜度對鏈表進行排序。
Sort a linked list in O(n log n) time using constant space complexity.
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
public ListNode sortList(ListNode head) {
if(head==null)return null;
if(head.next==null)return head;
ListNode p=head.next;
ListNode tail=head;
tail.next=null;
while(p!=null){
ListNode q=p.next;
p.next=null;
if(p.val<head.val){
p.next=head;
head=p;
}else{
ListNode pH=head;
boolean flag=false;
while(pH.next!=null){
if(pH.val<=p.val&&pH.next.val>=p.val){
p.next=pH.next;
pH.next=p;
flag=true;
break;
}
pH=pH.next;
}
if(!flag){
tail.next=p;
tail=p;
tail.next=null;
}
}
p=q;
}
return head;
}
}