zoukankan      html  css  js  c++  java
  • 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);
        }
    };
     
  • 相关阅读:
    什么是CMS
    TP3.2项目—微信推广页
    《实用技巧》——让你的网站变成响应式的3个简单步骤
    thinkphp分页带数据
    tp框架表单验证 及ajax
    tp框架做留言板
    随时修改添加,thinkphp小知识
    thinkphp使用ajax
    thinkphp修改和删除数据
    tp框架查询
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/7600187.html
Copyright © 2011-2022 走看看