• 148. Sort List


    https://leetcode.com/problems/sort-list/description/

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

    链表类题目找中间点使用双指针算法,要判断head -> next != nullptr,一定要首先判断head != nullptr。

    ListNode* findMid(ListNode* head){
            ListNode* fast = head -> next;
        ListNode* slow = head;
        while(fast != nullptr && fast -> next != nullptr){
            fast = fast -> next -> next;
            slow = slow -> next;
        }
           return slow;
    }

    思考归并排序算法,

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* merge(ListNode* left,ListNode* right){
            
            ListNode* dummy = new ListNode(-1);
            ListNode* p = dummy;
            while(left != nullptr && right != nullptr){
                if(left -> val < right -> val){
                    dummy -> next = left;
                    left = left -> next;
                    dummy = dummy -> next;
                }
                else{
                    dummy -> next = right;
                    right = right -> next;
                    dummy = dummy -> next;
                }
                
            }
            if(left != nullptr){
                dummy -> next = left;
            }
            if(right != nullptr){
                dummy -> next = right;
            }
            return p -> next;
        }
        ListNode* findMid(ListNode* head){
            ListNode* fast = head -> next;
            ListNode* slow = head;
            while(fast != nullptr && fast -> next != nullptr){
                fast = fast -> next -> next;
                slow = slow -> next;
            }
            return slow;
        }
        ListNode* mergeSort(ListNode* head){
            if(head == nullptr || head -> next == nullptr){
                return head;
            }
            
            ListNode* midNode = findMid(head);        
            ListNode* left = mergeSort(midNode -> next);
            midNode -> next = nullptr;
            ListNode* right = mergeSort(head);
            left = merge(left,right);
            return left;
            
            
        }
        ListNode* sortList(ListNode* head) {
            if(head == nullptr){
                return head;
            }        
            return mergeSort(head);
        }
    };
     
  • 相关阅读:
    RESTful API设计指南
    Ubuntu16.04 安装openssl
    shell while循环
    linux awk
    vim与shell切换
    shell for循环
    css 固定宽度,自动换行
    php-fpm 与 cgi
    ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/usr/local/mysql/tmp/mysql.sock'
    linux ps 命令参数详解
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/7600187.html
Copyright © 2020-2023  润新知