zoukankan      html  css  js  c++  java
  • [leedcode 148] Sort List

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

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
       /* Like the merge sort, we can do recursively:
            (1) Split the list (slow fast pointers)
            (2) sort the first part (merge sort)
            (3) sort the second part (merge sort)
            (4) merge the two parts (merge two sorted lists)
            注意函数返回值
            */
        public ListNode sortList(ListNode head) {
            if(head==null||head.next==null) return head;
            ListNode p= mergeSort(head);
            return p;
        }
        public ListNode mergeSort(ListNode head){
            if(head==null||head.next==null) return head;
            ListNode mid=getMiddleNode(head);
            ListNode p=mid.next;
            mid.next=null;
            ListNode first=mergeSort(head);
            ListNode second=mergeSort(p);
            return mergeTwoLists(first,second);
        }
        public ListNode getMiddleNode(ListNode head){
            ListNode newHead=new ListNode(-1);
            newHead.next=head;
            ListNode fast=head;
            ListNode slow=newHead;
            while(fast!=null&&fast.next!=null){
                fast=fast.next.next;
                slow=slow.next;
                
            }
            return slow;
        }
        public ListNode mergeTwoLists(ListNode first,ListNode second){
            ListNode newHead=new ListNode(-1);
            ListNode p=newHead;
            while(first!=null&&second!=null){
                if(first.val<second.val){
                    p.next=first;
                    p=first;
                    first=first.next;
                }else{
                    p.next=second;
                    p=second;
                    second=second.next;
                }
            }
            if(first!=null){
                p.next=first;
            }
            if(second!=null){
                p.next=second;
            }
            return newHead.next;
            
        }
    }
  • 相关阅读:
    《JavaScript高级程序设计》学习笔记12篇
    JS学习笔记12_优化
    JS学习笔记11_高级技巧
    JS学习笔记10_Ajax
    JS学习笔记9_JSON
    JS学习笔记8_错误处理
    为什么要在列表组件里写 Key ?
    var、let 和 const 的区别以及暂时性死区
    小程序性能优化要点
    Node require() 加载规则
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4694432.html
Copyright © 2011-2022 走看看