LinkedList - 148. Sort List
148. Sort List
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
思路:
题目意思很明确,给一个链表排序,排序的方式有很多,这里写一下归并排序。
代码:
java:
/**
* 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;
// 1. find mid of list
ListNode fast = head, slow = head, partHead = slow;
while (fast != null && fast.next != null) {
partHead = slow;
fast = fast.next.next;
slow = slow.next;
}
// 2. cut list as binary
partHead.next = null;
// 3. recursion cut
ListNode left = sortList(head);
ListNode right = sortList(slow);
// 4. merge list
return merge(left, right);
}
private ListNode merge(ListNode l1, ListNode l2) {
ListNode res = new ListNode(0), p = res;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
p.next = l1;
l1 = l1.next;
} else {
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if ( l1 != null) {
p.next = l1;
}
if (l2 != null) {
p.next = l2;
}
return res.next;
}
}