zoukankan      html  css  js  c++  java
  • [Linked List]Sort List

    otal Accepted: 59473 Total Submissions: 253637 Difficulty: Medium

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

     
    递归版本,代码比较好理解,并不符合题目要求,题目要求常量的空间
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* mergeSortList(ListNode* head1,ListNode* head2)
        {
            if(head1==NULL){
                return head2;
            }
            if(head2==NULL){
                return head1;
            }
            ListNode* newHead = head1->val < head2->val ?  head1:head2;
            newHead->next = head1->val < head2->val ? mergeSortList(head1->next,head2):mergeSortList(head1,head2->next);
            return newHead;
        }
        int getListLength(ListNode *head)
        {
            int cnt = 0;
            while(head){
                cnt++;
                head = head->next;
            }
            return cnt;
        }
        ListNode* sortList(ListNode* head) {
            int len = getListLength(head);
            if(len<=1){
                return head;
            }
            int cnt = len/2;
            ListNode* p = head,*pre=NULL;
            while(cnt--){
                pre = p;
                p = p->next;
            }
            ListNode* head2 = p;
            pre->next = NULL;
            ListNode* head1 = sortList(head);
            head2 = sortList(head2);
            return mergeSortList(head1,head2);
        }
    };
    Next challenges: (M) Insertion Sort List
  • 相关阅读:
    虚树
    最小树形图
    分块
    斜率优化
    单调队列优化DP
    树套树
    2-SAT
    莫队
    单调队列
    单调栈
  • 原文地址:https://www.cnblogs.com/zengzy/p/5041483.html
Copyright © 2011-2022 走看看