美文网首页
排序链表

排序链表

作者: 二进制的二哈 | 来源:发表于2019-12-22 23:02 被阅读0次

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

    在 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) {
            return sortAndMerge(head);
        }
    
        /**
         * 归并排序
         * @param head
         * @return
         */
        private ListNode sortAndMerge(ListNode head){
            if (head == null)
                return null;
            ListNode fast = head.next;
            ListNode slow = head;
            while(fast != null && fast.next != null){
                slow = slow.next;
                fast = fast.next.next;
            }
            ListNode rightNode = slow.next;
            slow.next = null;
            //此时slow节点就是中间节点,按这个节点分割
            ListNode left = head;
            if (head.next != null){
                left = sortAndMerge(head);
            }
            ListNode right = sortList(rightNode);
            return merge(left,right);
        }
    
        /**
         * 合并两个有序链表
         *  1->3
         *  2->4
         *  1->2->3->4
         * @param l1
         * @param l2
         * @return
         */
        private ListNode merge(ListNode l1,ListNode l2){
            ListNode head = new ListNode(0);
            ListNode cur = new ListNode(0);
            head.next = cur;
            while(l1 != null || l2 != null){
                if (l1 == null){
                    cur.next = l2;
                    break;
                }
                if (l2 == null){
                    cur.next = l1;
                    break;
                }
                if (l1.val > l2.val){
                    cur.next = l2;
                    l2 = l2.next;
                }else{
                    cur.next = l1;
                    l1 = l1.next;
                }
                cur = cur.next;
            }
            return head.next.next;
        }
    }
    

    相关文章

      网友评论

          本文标题:排序链表

          本文链接:https://www.haomeiwen.com/subject/vvyanctx.html