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;
        }
  • 相关阅读:
    Windows 系统变量大全
    linux编程
    CSS 对齐操作
    php 和 表单 简单交互
    HTML <input> placeholder 属性
    HTML <label> 标签
    Chap-4 Section 4.4 C++相关问题
    Chap-4 Section 4.3 COMMON块
    Chap-4 Section 4.2.4 指令修正方式
    Chap-4 Section 4.2.3 符号解析
  • 原文地址:https://www.cnblogs.com/skillking/p/9779948.html
Copyright © 2011-2022 走看看