让我们来写个算法吧,(6);链表排序

public static void main(String[] args) {
        ListNode l1 =new ListNode(1); 
        ListNode l2 =new ListNode(2);
        ListNode l3 =new ListNode(3);
        ListNode l4 =new ListNode(4);
        ListNode l5 =new ListNode(5);
        ListNode l6 =new ListNode(6);
        /*
         * l1.next =l4; l4.next =l6; l6.next =l2;
         */
        l2.next =l1;
        l3.next =l5;
        
        ListNode twoNumbers = new Main4().sortList(l2);
        while(twoNumbers!=null){
            System.out.print(twoNumbers.val +" ");
            twoNumbers = twoNumbers.next;
        }
    }
    
    //递归做归并排序
    public ListNode sortList(ListNode head) {
        if(head ==null || head.next ==null){
            return head;
        }
        ListNode first = head;
        ListNode mid =  getMid(head);
        ListNode second = mid.next;
        mid.next =null;
        first = sortList(first);
        second = sortList(second);
        return merge(first,second);
    }
    // 获取链表中节点
    private ListNode getMid(ListNode node){
        ListNode slow =node;
        ListNode fast = node.next;
        while( fast!=null && fast.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    
    // 合并两个有序链表
    private ListNode merge(ListNode first , ListNode second){
        if(first ==null){
            return second;
        }
        if(second == null){
            return first;
        }
        ListNode root = new ListNode(0);
        ListNode tmp = root;
        while(first!=null && second!=null){
            if(first.val < second.val){
            tmp.next = first;
            tmp =tmp.next;
            first =first.next;
            
            }else{
            tmp.next = second;
            tmp =tmp.next;
            second =second.next;
            }
        }
        
        if(first ==null){
            tmp.next = second;
        }
        if(second ==null){
            tmp.next = first;
        }
        return root.next;
    }

猜你喜欢

转载自www.cnblogs.com/leaveast/p/12524405.html