Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
难度:medium
题目:排列链表,时间复杂度为O(n logn) 空间复杂度为O(1).
思路:快速排序
Runtime: 232 ms, faster than 9.03% of Java online submissions for Sort List.
Memory Usage: 41.8 MB, less than 100.00% of Java online submissions for Sort List.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
quickSort(head, null);
return head;
}
private void quickSort(ListNode head, ListNode tail) {
if (head == tail) {
return;
}
int val = head.val;
ListNode prevSwapPtr = head;
for (ListNode ptr = head.next; ptr != tail; ptr = ptr.next) {
if (ptr.val < val) {
int t = prevSwapPtr.next.val;
prevSwapPtr.next.val = ptr.val;
ptr.val = t;
prevSwapPtr = prevSwapPtr.next;
}
}
head.val = prevSwapPtr.val;
prevSwapPtr.val = val;
quickSort(head, prevSwapPtr);
quickSort(prevSwapPtr.next, tail);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。