一、合并K个链表
将n个已经有序的链表,合并成一个链表,使之有序
【1】排序法实现,时间复杂度为O(KNlogKN)
【2】分治法实现,时间复杂度为O(KNlogK)
复制代码
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157#include<iostream > #include<vector> #include<algorithm> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) :val(x) ,next(NULL) {} }; //=====================使用vector进行排序================= bool cmp(const ListNode *headA, const ListNode* headB) { return headA->val < headB->val ; } class solution { public: ListNode* MergeKLists(vector<ListNode*> &lists) { vector<ListNode*> node_vec; for(int i = 0; i<lists.size(); i++) { ListNode* head = lists[i]; while(head) { node_vec.push_back(head); head = head->next ; } } if(node_vec.size() == 0) { return NULL; } sort(node_vec.begin(),node_vec.end(),cmp); for(int i = 1; i<node_vec.size(); i++) { node_vec[i-1]->next = node_vec[i]; } node_vec[ node_vec.size() -1 ]->next = NULL; return node_vec[0]; } }; //=====================使用分治法================= class solution { public: ListNode* MergetwoList(ListNode* headA,ListNode* headB) { ListNode Newhead(0); ListNode* ptr = &Newhead; while(headA && headB) { if(headA->val< headB->val ) { ptr->next = headA; headA =headA->next ; } else{ ptr->next = headB; headB = headB->next ; } ptr = ptr->next ; } if( headA ) { ptr->next = headA; } if( headB ) { ptr->next = headB; } return Newhead.next ; } ListNode* mergeKList(vector<ListNode*>&lists ) { if(lists.size() == 0) { return NULL; } if(lists.size() == 1) { return lists[0]; } if(lists.size() == 2) { return MergetwoList( lists[0], lists[1] );//注意这里直接返回,转向两个链表 } int mid = lists.size()/2; vector<ListNode *> List1 ; vector<ListNode *> List2 ; for(int i = 0; i < mid; i++) { List1.push_back(lists[i]); } for( int i = mid; i<lists.size(); i++ ) { List2.push_back(lists[i]); } ListNode* L1 = mergeKList(List1); ListNode* L2 = mergeKList(List2); return MergetwoList(L1,L2); } }; int main() { ListNode a(1); ListNode b(4); ListNode c(6); ListNode d(0); ListNode e(5); ListNode f(11); ListNode g(2); ListNode h(3); a.next = &b; b.next = &c; d.next = &e; e.next = &f; g.next = &h; solution solve; vector< ListNode* > Lists; Lists.push_back(&a); Lists.push_back(&d); Lists.push_back(&g); ListNode* head = solve.MergeKLists (Lists); while(head) { printf("%d ,", head->val ); head = head->next ; } return 0; }
最后
以上就是务实芹菜最近收集整理的关于【数据结构】合并K个有序链表(采用分治法、vector排序法分别实现)的全部内容,更多相关【数据结构】合并K个有序链表(采用分治法、vector排序法分别实现)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复