Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
多遍LeetCode之Merge Two Sorted Lists思想
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *mergeKLists(vector&lists) { if (lists.size() == 0) return NULL; while (lists.size()>1){ ListNode *mergelist = new ListNode(0); ListNode *p = lists[0]; ListNode *q = lists[lists.size()-1]; lists.pop_back(); lists[0]=mergeTwoLists(p, q); } return lists[0]; } ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode *list = new ListNode(0); ListNode *p, *q, *r; p = l1; q = l2; r = list; while (p&&q){ if (p->val <= q->val){ r->next = p; p = p->next; } else { r->next = q; q = q->next; } r = r->next; }//while r->next = q ? q : p; return list->next; } };