zoukankan      html  css  js  c++  java
  • Sort List

    Sort a linked list in O(n log n) time using constant space complexity.

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public  ListNode findMid(ListNode head) {
            ListNode pSlow = head;
            ListNode pFast = head;
            while (pFast.next!=null && pFast.next.next !=null) {
                pSlow = pSlow.next;
                pFast = pFast.next.next;
            }
            return pSlow;
        }
    
        public  ListNode sortList(ListNode head) {
            if (head==null||head.next==null){
                return head;
            }
            ListNode pMid = findMid(head);
            ListNode pMidRight = pMid.next;
            pMid.next = null;
            return merge(sortList(head),sortList(pMidRight));
        }
    
        public  ListNode merge(ListNode list1, ListNode list2) {
            if (list1==null || list2==null){
                return list1==null ?list2 : list1;
            }
            ListNode result;
            ListNode p1 = list1;
            ListNode p2 = list2;
            //初始化头部
            if (p1.val < p2.val) {
                result = p1;
                p1 = p1.next;
            } else {
                result = p2;
                p2 = p2.next;
            }
            ListNode p = result;
            //合并
            while (p1!=null && p2!=null) {
                if (p2.val < p1.val) {
                    p.next =  p2;
                    p2 = p2.next;
                    p = p.next;
                } else {
                    p.next = p1;
                    p1 = p1.next;
                    p = p.next;
                }
            }
            //补齐
            while (p1!=null) {
                p.next = p1;
                p1 = p1.next;
                p = p.next;
            }
            while (p2!=null) {
                p.next = p2;
                p2 = p2.next;
                p = p.next;
            }
            return result;
        }
    
    }
  • 相关阅读:
    NYOJ 132(最长回文子串)
    NYOJ 148(斐数求余)
    NYOJ 97
    NYOJ 206
    NYOJ 520(最大素因子的序数)
    数据库大型应用解决方案总结(转)
    SQL好的写法(转)
    WebService如何调试及测试工具
    刪除windows服務方法
    GhostDoc(注释生成工具)使用方法
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506822.html
Copyright © 2011-2022 走看看