美文网首页算法
leetcode--04. 链表排序

leetcode--04. 链表排序

作者: yui_blacks | 来源:发表于2018-11-15 20:33 被阅读0次

    题目:
    Sort a linked list in O(n log n) time using constant space complexity
    对链表排序,要求空间复杂度为O( nlogn )

    思路:
    可用归并,可以用快排

    public class Solution {
    
        public ListNode sortList(ListNode head) {
    
            quickSort(head, null);
    
            return head;
    
        }
    
        public static void quickSort(ListNode head, ListNode end) {
            if (head != end) {
                ListNode partion = partion(head);
                quickSort(head, partion);
                quickSort(partion.next, end);
            }
        }
    
        public static ListNode partion(ListNode head) {
            ListNode slow = head;
            ListNode fast = head.next;
            while (fast != null) {
                if (fast.val < head.val) {
                    slow = slow.next;
                    fast.val = slow.val ^ fast.val ^ (slow.val = fast.val);
                }
                fast = fast.next;
            }
            slow.val = head.val ^ slow.val ^ (head.val = slow.val);
            return slow;
        }
    }
    

    相关文章

      网友评论

        本文标题:leetcode--04. 链表排序

        本文链接:https://www.haomeiwen.com/subject/ufjufqtx.html