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; }
相关文章推荐
- Sort List - LeetCode 148
- leetcode148 Sort List
- LeetCode: Sort List [148]
- [LeetCode#148]Sort List
- [Leetcode]#148 Sort List
- leetcode_148 Sort List
- Leetcode:148_Sort List | O(nlogn)链表排序 | Medium
- leetcode题解-链表排序算法 147. Insertion Sort List && 148 . Sort List
- leetcode(148):Sort List
- Java for LeetCode 148 Sort List
- Leetcode[148]-Sort List
- [LeetCode 148] Sort List Solution
- leetcode148 sort list
- Leetcode 148 Sort List 单链表排序
- leetCode刷题归纳-List(148 Sort List)
- LeetCode 148 Sort List
- LeetCode 148: Sort List
- leetcode 148: Sort List
- leetcode[148]Sort List
- leetcode-Sort List-148