Sort a linked list in O(n log n) time using constant space complexity.
My Answer:
/**
* 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){
return head;
}
ListNode pivot = head;
ListNode pre = null;
ListNode first = null;
ListNode last = null;
pivot = head;
while(pivot != null){
if(pivot.val < head.val){
pre.next = pivot.next;
pivot.next = first;
first = pivot;
pivot = pre;
}else if(pivot.val > head.val){
pre.next = pivot.next;
pivot.next = last;
last = pivot;
pivot = pre;
}
pre = pivot;
pivot = pivot.next;
}
first = sortList(first);
last = sortList(last);
pivot = head;
while(pivot != null){
pre = pivot;
pivot = pivot.next;
}
pre.next = last;
if (first == null){
return head;
}
pivot = first;
while(pivot != null){
pre = pivot;
pivot = pivot.next;
}
pre.next = head;
return first;
}
}
題目來源: https://oj.leetcode.com/problems/sort-list/