zoukankan      html  css  js  c++  java
  • LeetCode Sort List

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

    归并排序的基本思想是:找到链表的middle节点,然后递归对前半部分和后半部分分别进行归并排序,最后对两个以排好序的链表进行Merge。

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        
            private ListNode getMiddle(ListNode head) {
            ListNode slow = head,fast=head;
            
            while (fast.next!=null&&fast.next.next!=null) {
                slow=slow.next;
                fast=fast.next.next;
                
            }
            return slow;
        }
        private ListNode     merge(ListNode a, ListNode b) {
            ListNode first=new ListNode(-1);
            ListNode curr = first;
            while (a!=null&&b!=null) {
                if (a.val<=b.val) {
                    curr.next=a;
                    a=a.next;
                }else {
                    curr.next=b;
                    b=b.next;
                }
                curr=curr.next;
            }
            
            if (a!=null) {
                curr.next=a;
            }else {
                curr.next=b;
            }
            return first.next;
            
        }
    
        public ListNode sortList(ListNode head) {
                if (head==null||head.next==null) {
                    return head;
                }
                ListNode middleNode = getMiddle(head);
                ListNode nextPart = middleNode.next;
                middleNode.next=null;
                return merge(sortList(head),sortList(nextPart));
    
        }
    }
  • 相关阅读:
    haproxy常用配置
    分区命令(大于2TB的分区)
    css基础-2 div布局
    css基础-1
    2.HTML5基本标签
    1.HTML基本结构、头部、注释
    AWK数组
    nginx rewrite 基础
    nginx location详解
    Linux命令练习.ziw
  • 原文地址:https://www.cnblogs.com/birdhack/p/3969664.html
Copyright © 2011-2022 走看看