zoukankan      html  css  js  c++  java
  • 让我们来写个算法吧,(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;
        }
  • 相关阅读:
    java内存模型
    如何保证消费者接收消息的顺序
    mysql事务隔离级别
    mysql加锁读
    mysql一致性读
    InnoDB锁
    JDK1.8中的线程池
    JDK1.8中HashMap实现
    物品推荐(基于物品的协同过滤算法)
    CRM 2013 生成自动编号
  • 原文地址:https://www.cnblogs.com/leaveast/p/12524405.html
Copyright © 2011-2022 走看看