zoukankan      html  css  js  c++  java
  • Sort List

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

     

    Merge sort

     先根据mid node把list 分割为 单个 node ,然后merge

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode sortList(ListNode head) {
           if(head == null || head.next == null)
            return head;
            ListNode fast = head.next.next;
            ListNode p = head;
    // while结束时 p指向的是中点的前一个节点
    while(fast != null && fast.next != null){ p = p.next; fast = fast.next.next; } // p is the mid node of the list // 这两行代码顺序不能换 ListNode h2 = sortList(p.next); p.next = null; // 把前半部分的merge sort结果 和后半部分的merge sort结果再merge sort return mergeSort(sortList(head), h2); } // merge two sorted list private ListNode mergeSort(ListNode h1, ListNode h2){ ListNode fakeNode = new ListNode(Integer.MIN_VALUE); ListNode runner = fakeNode; while(h1 != null && h2 != null){ if(h1.val < h2.val){ runner.next = h1; h1 = h1.next; }else{ runner.next = h2; h2 = h2.next; } runner = runner.next; } if(h1 != null){ runner.next = h1; } if(h2 != null){ runner.next = h2; } return fakeNode.next; } }
  • 相关阅读:
    2018 ACM 网络选拔赛 徐州赛区
    2018 ACM 网络选拔赛 焦作赛区
    2018 ACM 网络选拔赛 沈阳赛区
    poj 2289 网络流 and 二分查找
    poj 2446 二分图最大匹配
    poj 1469 二分图最大匹配
    poj 3249 拓扑排序 and 动态规划
    poj 3687 拓扑排序
    poj 2585 拓扑排序
    poj 1094 拓扑排序
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3556158.html
Copyright © 2011-2022 走看看