148. 排序链表

题目描述:

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

示例 1:

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

示例 2:

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

思路:

题目要求在 O(n log n) 时间复杂度下解题,在满足这个时间复杂度的常见算法有快速排序,归并排序,和堆排序。归并排序的重点是找到中间节点。

Java解法之冒泡排序(不满足题目对于时间复杂度的要求):

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        ListNode indexNode = head;
        ListNode startNode = head;
        if(head == null) return head;
        while(indexNode.next != null)
        {
            boolean exchangeflag = true;
            head = startNode;
            while(head.next != null){
                if(head.val > head.next.val)
                {
                    int temp = head.val;
                    head.val = head.next.val;
                    head.next.val = temp;
                    exchangeflag = false;
                }
                head = head.next;
            }
            if(exchangeflag)
            {
                break;
            }else{
                indexNode = indexNode.next;
            }  
        }
        return startNode;
    }
}

Java解法之归并排序:

/**
 * 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 slow = head, fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode temp = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(temp);
        ListNode h = new ListNode(0);
        ListNode ans = h;
        while(left != null && right != null)
        {
            if(left.val < right.val)
            {
                h.next = left;
                left = left.next;
            }else{
                h.next = right;
                right = right.next;
            }
            h = h.next;
        }
        h.next = left != null ? left : right;
        return ans.next;
    }
}

[图解] 归并排序

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list

你可能感兴趣的:(148. 排序链表)