您的位置:首页 > 其它

Leetcode#148 Sort List

2015-01-29 20:22 357 查看
原题地址

链表归并排序

真是恶心的一道题啊,哇了好多次才过。

代码:

void mergeList(ListNode *a, ListNode *b, ListNode *&h, ListNode *&t) {
h = t = NULL;
while (a && b) {
ListNode *c = NULL;
if (a->val <= b->val) {
c = a;
a = a->next;
}
else {
c = b;
b = b->next;
}
if (!h)
h = t = c;
else {
t->next = c;
t = t->next;
}
}
while (a) {
t->next = a;
t = t->next;
a = a->next;
}
while (b) {
t->next = b;
t = t->next;
b = b->next;
}
}

ListNode *sortList(ListNode *head) {
ListNode *prev = NULL;
ListNode *h1 = NULL;
ListNode *h2 = NULL;
ListNode *t1 = NULL;
ListNode *t2 = NULL;
ListNode *node = NULL;
int len = 0;

node = head;
while (node && (++len))
node = node->next;

for (int l = 1; l < len; l <<= 1) {
prev = NULL;
h1 = NULL;
h2 = NULL;
t1 = NULL;
t2 = NULL;
node = head;

while (node) {
h1 = t1 = node;
for (int i = 0; node && i < l; i++) {
t1 = node;
node = node->next;
}
if (t1)
t1->next = NULL;
h2 = t2 = node;
for (int i = 0; node && i < l; i++) {
t2 = node;
node = node->next;
}
if (t2)
t2->next = NULL;

ListNode *h, *t;
if (h2)
mergeList(h1, h2, h, t);
else {
h = h1;
t = t1;
}
if (!prev)
head = h;
else
prev->next = h;
t->next = node;
prev = t;
}
}

return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: