[itint5]合并K个有序链表
merge sort,leet code里面曾经做过。但一开始没这么写,遍历来做,效率n*k了,用了merge sort后,变成logn*k。
用了dummy node。同时要注意size为0的情况。
#include <climits> /*链表结点的定义(请不要在代码中定义该类型) struct ListNode { int val; ListNode *next; }; */ //lists包含k个链表的头结点,返回合并后链表头结点 ListNode* merge(vector<ListNode*> &lists) { if (lists.size() == 0) return NULL; int k = 1; while (k < lists.size()) { for (int i = 0; i < lists.size(); i += k*2) { int j = i + k; if (j >= lists.size()) break; // merge list i and j ListNode *dummy = new ListNode(); ListNode *last = dummy; while (lists[i] != NULL && lists[j] != NULL) { if (lists[i]->val < lists[j]->val) { last->next = lists[i]; last = last->next; lists[i] = lists[i]->next; } else { last->next = lists[j]; last = last->next; lists[j] = lists[j]->next; } } while (lists[i] != NULL) { last->next = lists[i]; last = last->next; lists[i] = lists[i]->next; } while (lists[j] != NULL) { last->next = lists[j]; last = last->next; lists[j] = lists[j]->next; } last->next = NULL; lists[i] = dummy->next; delete dummy; } k *= 2; } return lists[0]; }