Sort List

来源:互联网 发布:淘宝上螺蛳粉那家好吃 编辑:程序博客网 时间:2024/04/28 18:40

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

/** * 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 || head.next == null) {            return head;        }                ListNode fast = head;        ListNode slow = head;                while(fast.next != null && fast.next.next != null) {            fast = fast.next.next;            slow = slow.next;        }        ListNode left = head;        ListNode right = slow.next;        slow.next = null;            left = sortList(left);        right = sortList(right);                return merge(left, right);    }        private ListNode merge(ListNode left, ListNode right) {        if(left == null) {            return right;        }        if(right == null) {            return left;        }                ListNode preHead = new ListNode(-9999);        ListNode tail = preHead;                while(left != null && right != null) {            if(left.val < right.val) {                tail.next = left;                left = left.next;            } else {                tail.next = right;                right = right.next;            }            tail = tail.next;        }                if(left != null) {            tail.next = left;        }        if(right != null) {            tail.next = right;        }                return preHead.next;    }}


0 0
原创粉丝点击