# Sort List

ID: 98; medium

## Solution 1 (Java)

``````/**
* Definition for ListNode
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/

public class Solution {
/**
* @return: You should return the head of the sorted linked list, using constant space complexity.
*/
ListNode right = sortList(mid.next);
mid.next = null;
return merge(left, right);
}

while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}

private ListNode merge(ListNode left, ListNode right) {
ListNode dummy = new ListNode(0);

while (left != null && right != null) {
if (left.val <= right.val) {
left = left.next;
} else {
right = right.next;
}
}
if (left != null) head.next = left;
if (right != null) head.next = right;
return dummy.next;
}
}``````

### Notes

• This is the merge sort version of Sort List.

• Time complexity: `O(nlogn)`

## Solution 2 (Java)

``````/**
* Definition for ListNode
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/

public class Solution {
/**
* @return: You should return the head of the sorted linked list, using constant space complexity.
*/

ListNode leftDummy = new ListNode(0), leftTail = leftDummy;
ListNode midDummy = new ListNode(0), midTail = midDummy;
ListNode rightDummy = new ListNode(0), rightTail = rightDummy;

} else if (head.val > mid.val) {
} else {
}
}

leftTail.next = null;
midTail.next = null;
rightTail.next = null;

ListNode left = sortList(leftDummy.next);
ListNode right = sortList(rightDummy.next);
return concat(left, midDummy.next, right);
}

while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}

private ListNode concat(ListNode left, ListNode mid, ListNode right) {
ListNode dummy = new ListNode(0), tail = dummy;
tail.next = left; tail = moveTail(tail);
tail.next = mid; tail = moveTail(tail);
tail.next = right; tail = moveTail(tail);
return dummy.next;
}

private ListNode moveTail(ListNode tail) {
if (tail == null) return null;
while (tail.next != null) {
tail = tail.next;
}
return tail;
}
}``````

• Quick sort

Last updated