leetcode_c++:链表:Merge k Sorted Lists(023)
2016-07-15 19:49
399 查看
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
//merge k个有序链表成一个
归并排序
1. 二分思想
2. 把每个list和与他相邻的链表组合,规模少一半。重复
//merge k个有序链表成一个
算法
O(nklgk)归并排序
1. 二分思想
2. 把每个list和与他相邻的链表组合,规模少一半。重复
#include <iostream> #include <vector> #include<cmath> #include <algorithm> using namespace std; struct ListNode{ int val; ListNode* next; ListNode(int x):val(x),next(NULL){} }; /* int ListInsert(ListNode* L, int pos,int data){ int j=1; ListNode *p,*s; p=L; while(p && j<pos){ p=p->next; ++j; } if(!p||j>pos) return 0; s=new ListNode(0); s->val=data; s->next=p->next; p->next=s; return 1; } // 打印 int ListTraverse(ListNode* L){ ListNode *p=L->next; while(p){ cout<<p->val<<endl; p=p->next; } printf("\n"); return 1; } */ //leetcode------------------- class Solution { public: ListNode* merge2Lists(ListNode *l1, ListNode *l2){ ListNode* dummy=new ListNode(-1); ListNode* current=dummy; while(l1 !=NULL && l2 !=NULL){ if(l1->val<l2->val){ current->next=l1; l1=l1->next; }else{ current->next=l2; l2=l2->next; } current=current->next; } if(l1!=NULL) current->next=l1; else current->next=l2; return dummy->next; } ListNode* mergeKLists(vector<ListNode*>& lists) { int sz= lists.size(); if(sz==0) return NULL; while(sz>1){ int k=(sz+1)/2; for(int i=0;i<sz/2;i++) lists[i]=merge2Lists(lists[i],lists[i+k]); sz=k; } return lists[0]; } }; //------------- //---数组数据插入链表---------------- ListNode* createList(int a[],int n){ ListNode* head=NULL,*p=NULL; for(int i=0;i<n;i++){ if(head==NULL){ head=p=new ListNode(a[i]); }else{ p->next=new ListNode(a[i]); p=p->next; } } return head; } void printList(ListNode* h){ while(h!=NULL){ printf("%d ",h->val); h=h->next; } printf("\n"); } //------------- int main(){ Solution s; int a[]={1,3,5,6,7,10}; int b[]={0,4,6,8,11,20,30,40}; ListNode* p1=createList(a,sizeof(a)/sizeof(int)); ListNode* p2=createList(b,sizeof(b)/sizeof(int)); //printList(p1); //printList(p2); // printList(s.merge2Lists(p1,p2)); srand(time(0)); vector<ListNode*> v; for(int i=0;i<50;i++) v.push_back(new ListNode(random()%100)); //cout<<endl; printList(s.mergeKLists(v)); return 0; }
相关文章推荐
- C语言中常用的函数及注意事项
- 1069. The Black Hole of Numbers (20)
- Linked List Cycle II
- C语言零散知识学习
- c语言里面TMin不能写成-2147483648的原因
- Emacs as a C/C++ Editor/IDE (Part 2)
- C语言 操作符和表达式
- Cpp环境【POJ 2375】【Vijos1642】雪场缆车
- Linked List Cycle
- 《30天自制操作系统》 day0-day2小结
- July 15th 模拟赛C T3 最小最大和 Solution
- 洛谷 P1079 [NOIP2012 D1T1] Vigenère 密码
- if选择结构
- C++ 通过ADO.Net实现与MySql数据库连接 入门教程
- July 15th 模拟赛C T2 积木游戏 Solution
- 常见排序算法C/C++实现总结
- C++实现RTMP协议发送H.264编码及AAC编码的音视频
- c++动态链接
- 洛谷 P1330 封锁阳光大学
- Observer观察者模式