zoukankan      html  css  js  c++  java
  • 148. Sort List

    一、题目

      1、审题

      

      2、分析

        将一个链表节点进行排序,时间复杂度为 NLogN, 且使用常数的空间复杂度。

    二、解答

      1、思路:

          采用归并排序的思想。

          ①、将链表进行切割

          ②、将切割的链表进行排序

          ③、合并切割的链表。

        public ListNode sortList(ListNode head) {
            if(head == null || head.next == null)
                return head;
            
            ListNode prev = null;
            ListNode slow = head;
            ListNode fast = head;
            
            // step 1. cut the list to two halves
            while(fast != null && fast.next != null) {
                prev = slow;
                slow = slow.next;
                fast = fast.next.next;
            }
            
            prev.next = null;
            
            // step 2. sort each half
            ListNode l1 = sortList(head);
            ListNode l2 = sortList(slow);
            
            // step 3. merge l1 and l2
            return merge(l1, l2);
        }
        
        private ListNode merge(ListNode l1, ListNode l2) {
            
            ListNode lNode = new ListNode(0);
            ListNode pNode = lNode;
            
            while(l1 != null && l2 != null) {
                if(l1.val < l2.val) {
                    pNode.next = l1;
                    l1 = l1.next;
                }
                else {
                    pNode.next = l2;
                    l2 = l2.next;
                }
                pNode = pNode.next;
            }
            
            if(l1 != null)
                pNode.next = l1;
            if(l2 != null)
                pNode.next = l2;
            
            return lNode.next;
        }
  • 相关阅读:
    IDEA右键新建时没有Java Class选项
    捕获摄像头视频VC
    重叠IO与IOCP
    (八)内存管理与内存分配
    DebugView使用详解
    (六) 中断机制
    (五) proc文件系统
    bash 之备份文件
    bash 遍历目录文件
    (四) linux内核模块编程
  • 原文地址:https://www.cnblogs.com/skillking/p/9779948.html
Copyright © 2011-2022 走看看