LeetCode148. 排序链表

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

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4
示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

解题思路:
归并排序

/**
 * 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 p1 = head;
        ListNode p2 = head.next;
        while (p2!=null) {
            p2 = p2.next;
            if (p2 == null)
                break;
            p2 = p2.next;
            p1 = p1.next;
        }
        p2 = p1.next;
        p1.next = null;
        p1 = head;
        //排序左边
        p1 = sortList(p1);
        //排序右边
        p2 = sortList(p2);
        //合并
        p1 = mergeTwoLists(p1,p2);
        return p1;
    }


    //合并两个排序链表
    public ListNode mergeTwoLists(ListNode left, ListNode right) {
        if (left == null) return right;
        if (right == null) return left;
        if (left.val <= right.val) {
            left.next = mergeTwoLists(left.next, right);
            return left;
        } else {
            right.next = mergeTwoLists(right.next, left);
            return right;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u012485480/article/details/80826001
今日推荐