使用快速排序算法對列表進行排序——Leetcode系列(四)

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

My Answer:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null){
            return head;
        }
        ListNode pivot = head;
        ListNode pre = null;
        ListNode first = null;
        ListNode last = null;
        pivot = head;
        while(pivot != null){
            if(pivot.val < head.val){
                pre.next = pivot.next;
                pivot.next = first;
                first = pivot;
                pivot = pre;
            }else if(pivot.val > head.val){
                pre.next = pivot.next;
                pivot.next = last;
                last = pivot;
                pivot = pre;
            }
            pre = pivot;
            pivot = pivot.next;
        }
        
        first = sortList(first);
        last = sortList(last);
        
        pivot = head;
        while(pivot != null){
            pre = pivot;
            pivot = pivot.next;
        }
        pre.next = last;
        if (first == null){
            return head;
        }
        pivot = first;
        while(pivot != null){
            pre  = pivot;
            pivot = pivot.next;
        }
        pre.next = head;
        return first;
    }
}

題目來源: https://oj.leetcode.com/problems/sort-list/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章