sort-list java code

来源:互联网 发布:精神发育迟缓症状知乎 编辑:程序博客网 时间:2024/06/05 11:33

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 slow = head;        ListNode fast = head.next;        while (fast != null && fast.next != null) {            slow = slow.next;            fast = fast.next.next;        }        ListNode right = sortList(slow.next);        slow.next = null;        ListNode left = sortList(head);        // /待左右两边各自有序,进行归并即可        ListNode temp_head = new ListNode(0);        ListNode temp_node = temp_head;        while (left != null && right != null) {            if (left.val < right.val) {                temp_node.next = left;                left = left.next;            } else {                temp_node.next = right;                right = right.next;            }            temp_node = temp_node.next;        }        if (left != null)            temp_node.next = left;        if (right != null)            temp_node.next = right;        return temp_head.next;    }}