# LeetCode 题解（140）: Sort List

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

C++版：

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
return NULL;

int i = 0;
int k = pow(2, i);

while (true) {
int pass = 0;
if (pass == 1)
break;
k = pow(2, ++i);
}
}

ListNode* mergeTwoSortedLists(ListNode* p, int k, int& pass) {
if (p == NULL)
return NULL;

pass++;
int i = 0;
ListNode* q = p;
while (i < k && q != NULL) {
q = q->next;
i++;
}

if (q == NULL)
return p;

if (p->val <= q->val)
else

int count1 = 0, count2 = 0;
while (count1 < k && count2 < k && q != NULL) {
while (p->val <= q->val && count1 + 1 < k && p->next->val <= q->val) {
p = p->next;
count1++;
}
if (p->val <= q->val) {
ListNode* temp = p->next;
p->next = q;
p = temp;
count1++;
}
if (count1 == k) {
while (count2 + 1 < k && q->next != NULL) {
q = q->next;
count2++;
}
q->next = mergeTwoSortedLists(q->next, k, pass);
break;
}
while (q->val < p->val && count2 + 1 < k && q->next != NULL && q->next->val < p->val) {
q = q->next;
count2++;
}
if (q->val < p->val) {
ListNode* temp = q->next;
q->next = p;
q = temp;
count2++;
}
if (count2 == k || q == NULL) {
while (count1  + 1 < k) {
p = p->next;
count1++;
}
p->next = mergeTwoSortedLists(q, k, pass);
break;
}
}
}
};


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

PointbreakLALALA

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
01-08 1095

10-21
03-17 202
05-05 106
06-06 818
01-05 2579