148 Sort List 链表上的归并排序和快速排序

在使用O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

详见:https://leetcode.com/problems/sort-list/description/

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;
        }
        ListNode slow=head;
        ListNode fast=head;
        ListNode mid=null;
        while(fast!=null&&fast.next!=null){
            mid=slow;
            slow=slow.next;
            fast=fast.next.next;
        }
        mid.next=null;
        return mergeSort(sortList(head),sortList(slow));
    }
    private ListNode mergeSort(ListNode low,ListNode high){
        ListNode helper=new ListNode(-1);
        ListNode cur=helper;
        while(low!=null&&high!=null){
            if(low.val<high.val){
                cur.next=low;
                low=low.next;
            }else{
                cur.next=high;
                high=high.next;
            }
            cur=cur.next;
        }
        cur.next=low!=null?low:high;
        return helper.next;
    }
}

链表上的快速排序:

/**
 * 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;
        }
        quickSort(head,null);
        return head;
    }   
    private void quickSort(ListNode begin,ListNode end){
        if(begin!=end){
            ListNode seq=getSeperator(begin,end);
            quickSort(begin,seq);
            quickSort(seq.next,end);
        }
    }
    private ListNode getSeperator(ListNode begin,ListNode end){
        ListNode first=begin;
        ListNode second=begin.next;
        int pivot=first.val;
        while(second!=end){
            if(second.val<pivot){
                first=first.next;
                swap(first,second);
            }
            second=second.next;
        }
        swap(first,begin);
        return first;
    }
    private void swap(ListNode a,ListNode b){
        int tmp=a.val;
        a.val=b.val;
        b.val=tmp;
    }
}
原文地址:https://www.cnblogs.com/xidian2014/p/8727493.html