Leetcode#148 Sort List

原题地址

链表归并排序

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

代码:

 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 = ; node = head;
while (node && (++len))
node = node->next; for (int l = ; l < len; l <<= ) {
prev = NULL;
h1 = NULL;
h2 = NULL;
t1 = NULL;
t2 = NULL;
node = head; while (node) {
h1 = t1 = node;
for (int i = ; node && i < l; i++) {
t1 = node;
node = node->next;
}
if (t1)
t1->next = NULL;
h2 = t2 = node;
for (int i = ; 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;
}
上一篇:利用传入的Type类型来调用范型方法的解决方案


下一篇:laravel-模板引擎Blade