zoukankan      html  css  js  c++  java
  • LeetCode之“链表”:Sort List

      题目链接

      题目要求:

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

      满足O(n log n)时间复杂度的有快排、归并排序、堆排序。在这里采用的是归并排序(空间复杂度O(log n)),具体程序如下:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* merge(ListNode* l1, ListNode* l2)
    12     {
    13         ListNode *dummy = new ListNode(0);
    14         ListNode *head = nullptr, *start = dummy;
    15         while(l1 && l2)
    16         {
    17             if(l1->val < l2->val)
    18             {
    19                 start->next = l1;
    20                 l1 = l1->next;
    21             }
    22             else 
    23             {
    24                 start->next = l2;
    25                 l2 = l2->next;
    26             }
    27             start = start->next;
    28         }
    29         
    30         if(!l1)
    31             start->next = l2;
    32         else if(!l2)
    33             start->next = l1;
    34         
    35         head = dummy->next;
    36         delete dummy;
    37         dummy = nullptr;
    38         
    39         return head;
    40     }
    41     
    42     ListNode* mergeSort(ListNode* head)
    43     {
    44         if(!head->next)
    45             return head;
    46         
    47         ListNode *slow = head, *fast = head;
    48         ListNode *preNode = slow;
    49         while(fast && fast->next)
    50         {
    51             preNode = slow;
    52             slow = slow->next;
    53             fast = fast->next->next;
    54         }
    55         preNode->next = nullptr;
    56         
    57         ListNode *left = mergeSort(head);
    58         ListNode *right = mergeSort(slow);
    59         return merge(left, right);
    60     }
    61 
    62     ListNode* sortList(ListNode* head) {
    63         if(!head || !head->next)
    64             return head;
    65             
    66         return mergeSort(head);
    67     }
    68 };
  • 相关阅读:
    bzoj1415 NOI2005聪聪和可可
    Tyvj1952 Easy
    poj2096 Collecting Bugs
    COGS 1489玩纸牌
    COGS1487 麻球繁衍
    cf 261B.Maxim and Restaurant
    cf 223B.Two Strings
    cf 609E.Minimum spanning tree for each edge
    cf 187B.AlgoRace
    cf 760B.Frodo and pillows
  • 原文地址:https://www.cnblogs.com/xiehongfeng100/p/4604431.html
Copyright © 2011-2022 走看看