148.Sort List

Linked List, Easy

Question

Sort a linked list in O(nlogn) time using constant space complexity.

Example 1:

1
2
Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

1
2
Input: -1->5->3->4->0
Output: -1->0->3->4->5

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* 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 mid = findMid(head);
ListNode right = sortList(mid.next);
mid.next = null;
ListNode left = sortList(head);
return merge(left, right);
}
public ListNode findMid(ListNode head){
ListNode fast = head, slow = head, mid = null;
while(fast!=null && fast.next!=null){
mid = slow;
fast = fast.next.next;
slow = slow.next;
}
return mid;
}
public ListNode merge(ListNode l1, ListNode l2){
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while(l1!=null && l2!=null){
if(l1.val < l2.val){
head.next = l1;
l1 = l1.next;
}else{
head.next = l2;
l2 = l2.next;
}
head = head.next;
}
if(l1!=null)
head.next = l1;
else
head.next = l2;
return dummy.next;
}
}

Using fast and slow pointer to find middle element in LinkedList

t = length/2

slow position = t v = length/2 1 = length/2

Running time: O(nlgn)