您的位置:首页 > 其它

【LeetCode】Merge k Sorted Lists

2014-04-22 19:23 288 查看
Merge k sorted
linked lists and return it as one sorted list. Analyze and describe its complexity.

思路:很简单,就是讲两个排序单链表合并即可,其实也可以是归并方式来做,都差不多。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:

ListNode *mergeList(ListNode *head1,ListNode *head2) {
if(head1==NULL)return head2;
if(head2==NULL)return head1;
ListNode *head=NULL;
if(head1->val>head2->val){
head=head2;
head2=head2->next;
}else{
head=head1;
head1=head1->next;
}
head->next=NULL;
ListNode *cur=head;
while(head1!=NULL&&head2!=NULL){
if(head1->val>head2->val){
cur->next=head2;
head2=head2->next;
}else{
cur->next=head1;
head1=head1->next;
}
cur=cur->next;
}
if(head1==NULL&&head2==NULL)return head;
else if(head1==NULL)cur->next=head2;
else cur->next=head1;
return head;

}

ListNode *mergeKLists(vector<ListNode *> &lists) {
int nsize=lists.size();
if(nsize==0)return NULL;
ListNode *head1=lists[0];
if(nsize==1)return head1;
for(int i=1;i<nsize;i++){
ListNode *head2=lists[i];
head1=mergeList(head1,head2);
}
return head1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: