美文网首页程序员
力扣 148 排序链表

力扣 148 排序链表

作者: zhaojinhui | 来源:发表于2020-11-20 05:05 被阅读0次

    题意:给一个乱序的链表,把它排序输出

    思路:

    1. 找出二分链表的节点
    2. 对每一半进行递归排序
    3. 把拍好序的两半merge到一个,并返回

    思想:归并排序

    复杂度:时间O(nlgn),空间O(n)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode sortList(ListNode head) {
            if(head == null || head.next == null)
                return head;
            ListNode newhead = new ListNode(0);
            newhead.next = head;
            
            ListNode n1 = newhead;
            ListNode n2 = newhead;
            while(n1 != null && n1.next != null) {
                n1 = n1.next.next;
                n2 = n2.next;
            }
            n1 = n2.next;
            n2.next = null;
    
            n1 = sortList(n1);
            n2 = sortList(newhead.next);
    
            newhead = new ListNode(0);
            ListNode runner = newhead;
            while(n1 != null && n2 != null) {
                if(n1.val < n2.val) {
                    ListNode temp = n1.next;
                    n1.next = null;
                    runner.next = n1;
                    runner = n1;
                    n1 = temp;
                } else {
                    ListNode temp = n2.next;
                    n2.next = null;
                    runner.next = n2;
                    runner = n2;
                    n2 = temp;
                }
            }
            if(n1 != null)
                runner.next = n1;
            if(n2 != null)
                runner.next = n2;
            return newhead.next;
        }
    }
    

    相关文章

      网友评论

        本文标题:力扣 148 排序链表

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