leetcode: Merge k Sorted Lists
http://oj.leetcode.com/problems/merge-k-sorted-lists/
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路:
不停的做两两合并就可以了。
1 class Solution { 2 public: 3 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 4 ListNode *head = NULL, *tail = NULL, *tmp; 5 6 while ((l1 != NULL) && (l2 != NULL)) { 7 if (l1->val < l2->val) { 8 tmp = l1; 9 l1 = l1->next; 10 } 11 else { 12 tmp = l2; 13 l2 = l2->next; 14 } 15 16 if (NULL == head) { 17 head = tail = tmp; 18 } 19 else { 20 tail->next = tmp; 21 tail = tmp; 22 } 23 } 24 25 tmp = (NULL == l1) ? l2 : l1; 26 27 if (head != NULL) { 28 tail->next = tmp; 29 30 return head; 31 } 32 else { 33 return tmp; 34 } 35 } 36 37 ListNode *mergeKLists(vector<ListNode *> &lists) { 38 if (0 == lists.size()) { 39 return NULL; 40 } 41 42 ListNode *p = lists[0]; 43 for (int i = 1; i < lists.size(); ++i) { 44 p = mergeTwoLists(p, lists[i]); 45 } 46 47 return p; 48 } 49 };