Skip to content

Commit 3458e7c

Browse files
committed
Add merge k lists solutions
1 parent 1a94fd5 commit 3458e7c

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

leetcode/linked_list/merge_two_sorted_list.cpp renamed to leetcode/linked_list/merge_sorted_list.cpp

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22
* @Author: Chacha
33
* @Date: 2019-01-06 22:50:09
44
* @Last Modified by: Chacha
5-
* @Last Modified time: 2019-01-06 23:13:13
5+
* @Last Modified time: 2019-02-18 22:11:29
66
*/
77

88
#include<iostream>
99
#include<string>
10+
#include<vector>
1011
using namespace std;
1112

1213
/**
@@ -59,6 +60,67 @@ class Solution {
5960
lastNode->next = (l1 != NULL) ? l1 : l2;
6061
return dummy->next;
6162
}
63+
64+
/**
65+
* Merge k sorted linked lists and return it as one sorted list.
66+
*
67+
* Source:
68+
* https://leetcode.com/problems/merge-k-sorted-lists/
69+
* https://leetcode.com/problems/merge-k-sorted-lists/solution/
70+
* https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73014#
71+
*
72+
*
73+
* Solution 1
74+
* @param lists: a list of ListNode
75+
* @return: The head of one sorted list.
76+
*/
77+
ListNode* mergeKLists1(vector<ListNode *> &lists) {
78+
if (lists.empty()) return NULL;
79+
80+
ListNode* dummy = new ListNode(INT_MAX);
81+
ListNode* lastNode = dummy;
82+
83+
while(true) {
84+
int count = 0;
85+
int index = -1, tempVal = INT_MAX;
86+
87+
for(int i = 0; i != lists.size(); ++i) {
88+
if (lists[i] == NULL) {
89+
++count;
90+
91+
if (count == lists.size()) {
92+
lastNode->next = NULL;
93+
return dummy->next;
94+
}
95+
continue;
96+
}
97+
98+
// choose the min value in non-NULL ListNode
99+
if (lists[i] != NULL && lists[i]->val <= tempVal) {
100+
tempVal = lists[i]->val;
101+
index = i;
102+
}
103+
}
104+
105+
lastNode->next = lists[index];
106+
lastNode = lastNode->next;
107+
lists[index] = lists[index]->next;
108+
}
109+
}
110+
111+
/**
112+
* Solution 2
113+
*/
114+
ListNode* mergeKLists2(vector<ListNode *> &lists) {
115+
if (lists.empty()) return NULL;
116+
117+
ListNode* head = lists[0];
118+
for(int i = 1; i != lists.size(); ++i) {
119+
head = mergeTwoLists(head, lists[i]);
120+
}
121+
122+
return head;
123+
}
62124
};
63125

64126
/* Function to print nodes in a given linked list */

0 commit comments

Comments
 (0)