标签:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
程序如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* head= new ListNode(0); ListNode* p=head;//head->next为返回的指针 while(1) { if(l1 && l2){ if(l1->val<l2->val){ p->next=l1; p=l1; l1=l1->next; } else{ p->next=l2; p=l2; l2=l2->next; } } else if(l1 && l2==NULL){ p->next=l1; break; } else if(l1==NULL && l2){ p->next=l2; break; } else{ break; } } return head->next; } ListNode* mergeKLists(vector<ListNode*>& lists) { if(lists.size()==0) return NULL; vector<ListNode*> old_lists;//合并前的lists vector<ListNode*> new_lists;//合并后的lists old_lists.clear();new_lists.clear(); for(int i=0;i<lists.size();i++) old_lists.push_back(lists[i]); while(1) { if(old_lists.size()==1) break;//合并成一条链表就输出 int cnt=0; for(int i=0;i<old_lists.size()/2;i++) { new_lists.push_back(mergeTwoLists(old_lists[cnt],old_lists[cnt+1])); cnt+=2; } if(cnt<old_lists.size())//如果链表数是奇数,则合并完前面的两两组合后,还要加入最后一个链表 new_lists.push_back(old_lists[cnt]); old_lists.clear(); for(int i=0;i<new_lists.size();i++) old_lists.push_back(new_lists[i]); new_lists.clear(); } return old_lists[0]; }}; |
LeetCode 23. Merge k Sorted Lists
标签:
原文地址:http://www.cnblogs.com/gremount/p/5771223.html