zoukankan      html  css  js  c++  java
  • Sort List

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

     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 *sortList( ListNode *head )
    12     {
    13         vector<int> vec;
    14         ListNode *p = head;
    15         while( p != NULL )
    16         {
    17             vec.push_back( p->val );
    18             p = p->next;
    19         }
    20         
    21         vector<int> tmp( vec.size() );
    22         
    23         mergeSort( vec, tmp, 0, vec.size() - 1 );
    24         
    25         p = head;
    26         for(vector<int>::iterator it = vec.begin(); it != vec.end(); it++, p = p->next)
    27             p->val = *it;
    28             
    29         return head;
    30     }
    31     
    32     void mergeSort( vector<int> &vec, vector<int> &tmp, int left, int right )
    33     {
    34         if( left < right )
    35         {
    36             int center = ( left + right ) / 2;
    37             mergeSort( vec, tmp, left, center );
    38             mergeSort( vec, tmp, center + 1, right );
    39             merge( vec, tmp, left, center + 1, right );
    40         }
    41     }
    42     
    43     void merge( vector<int> &vec, vector<int> &tmp, int leftPos, int rightPos, int rightEnd )
    44     {
    45         int leftEnd = rightPos - 1;
    46         int tmpPos = leftPos;
    47         int numElements = rightEnd - leftPos + 1;
    48         
    49         while(leftPos <= leftEnd && rightPos <= rightEnd)
    50             if(vec[leftPos] < vec[rightPos])
    51                 tmp[tmpPos++] = vec[leftPos++];
    52             else
    53                 tmp[tmpPos++] = vec[rightPos++];
    54                 
    55         while(leftPos <= leftEnd)
    56             tmp[tmpPos++] = vec[leftPos++];
    57             
    58         while(rightPos <= rightEnd)
    59             tmp[tmpPos++] = vec[rightPos++];
    60             
    61         for(int i = 0; i < numElements; i++, rightEnd--)
    62             vec[rightEnd] = tmp[rightEnd];
    63     }
    64 };
  • 相关阅读:
    迭代器与生成器
    11.30
    函数及装饰器
    C#For循环
    C#变量与数据类型
    C#输入输出
    JDK10新特性--var
    idea插件Lombok使用
    NodeJs操作文件-写入、修改、删除、追加、读取文件内容、判断文件是否存在
    mongodb多条件分页查询(mongoTemplate分页查询)
  • 原文地址:https://www.cnblogs.com/YQCblog/p/3970214.html
Copyright © 2011-2022 走看看