【Leetcode】148. Sort List

本小妞迷上赌 提交于 2020-01-13 13:21:07

题目地址:

https://leetcode.com/problems/sort-list/

对一个链表排序。可以使用归并排序。

public class Solution {
    public ListNode sortList(ListNode head) {
        if (head == null) {
            return null;
        }
    
        return mergeSort(head);
    }
    
    private ListNode mergeSort(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode l1 = head;
        // 这里的mid取的是整个链表的中点,如果链表长为偶数则取的是靠前的中点
        ListNode mid = findMid(head);
        ListNode l2 = mid.next;
        // 要将链表从中间断开,才能继续归并排序
        mid.next = null;
    
        ListNode list1 = mergeSort(l1);
        ListNode list2 = mergeSort(l2);
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        while (list1 != null || list2 != null) {
            if (list1 == null) {
                cur.next = list2;
                break;
            }
            if (list2 == null) {
                cur.next = list1;
                break;
            }
            if (list1.val <= list2.val) {
                cur.next = list1;
                list1 = list1.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        return dummy.next;
    }
    
    private ListNode findMid(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode slow = head, fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
    }
}

时间复杂度O(nlogn)O(n\log n)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!