Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路:开始做过两两合并的链表,此时做k路合并,即将k个链表进行合并,可以先将这k个链表进行两两合并,知道合并为一个链表。直接调用前面写过的两两合并的例子。
C++代码实现:
#include#include #include using namespace std;//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.empty()) return NULL; if(lists.size()==1) return lists[0]; int i; vector temp=lists; while(lists.size()!=1) { temp=lists; lists.clear(); for(i=0; i<(int)temp.size(); i=i+2) { ListNode *L=NULL; if(i+1 val<=q->val) { pre=p; p=p->next; } else { qq=q; q=q->next; if(l1==p) { qq->next=l1; l1=qq; pre=p=l1; continue; } qq->next=p; pre->next=qq; pre=qq; } } while(q) { pre->next=q; pre=q; q=q->next; } } if(l1==NULL) l1=l2; return l1; } void createList(ListNode *&head,int *arr) { ListNode *p=NULL; int i=0; for(i=0; i<5; i++) { if(head==NULL) { head=new ListNode(arr[i]); if(head==NULL) return; } else { p=new ListNode(arr[i]); p->next=head; head=p; } } }};int main(){ Solution s; ListNode *L1=NULL; ListNode *L2=NULL; ListNode *L3=NULL; ListNode *L=NULL; int arr1[5]= { 11,9,7,5,3}; int arr2[5]= { 10,8,6,4,2}; int arr3[5]={ 14,13,12,1,0}; s.createList(L1,arr1); s.createList(L2,arr2); s.createList(L3,arr3); vector lists={L1,L2,L3}; L=s.mergeKLists(lists); while(L) { cout< val<<" "; L=L->next; }}
运行结果:
//不需要使用临时空间,每次直接将合并之后的两个链表从lists中删除,兩两合并后的结果插入到list的结尾class Solution {public:ListNode *mergeKLists(vector&lists) { if(lists.empty()) return NULL; if(lists.size()==1) return lists[0]; ListNode *L=NULL; while(lists.size()!=1) { auto iter=lists.begin(); ListNode *first=*iter; lists.erase(iter); iter=lists.begin(); ListNode *second=*iter; lists.erase(iter); L=mergeTwoLists(first,second); lists.push_back(L); } return lists[0]; } ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if(l1==NULL) return l2; if(l2==NULL) return l1; ListNode *head=NULL; ListNode *r=NULL; ListNode *p=l1; ListNode *q=l2; if(p->val val) { head=p; r=head; p=p->next; } else { head=q; r=head; q=q->next; } r->next=NULL; while(p&&q) { if(p->val val) { r->next=p; r=p; p=p->next; } else { r->next=q; r=q; q=q->next; } r->next=NULL; } if(q) p=q; r->next=p; return head; }};