Leetcode题解-23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.(链表元素从小到大排序)
思路
思路1:之前做过合并2个有序链表的题目,这题无非就是把合并两条链表后产生的新链表和剩下的链表中的一条进行合并,直到没有剩下的链表
思路2:类似归并排序,每次合并两个链表,然后删掉已经合并的链表并且把新的链表加入链表集合的尾端,一直重复直到集合只有一个链表
代码
思路1
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0) return nullptr;
ListNode* ptr = NULL;
while(lists.size() != 0){
ptr = mergeTwo(ptr, lists[0]);
lists.erase(lists.begin());
}
return ptr;
}
ListNode* mergeTwo(ListNode* l1, ListNode* l2){
ListNode head(-1);
ListNode *newlist = &head;
while(l1 && l2){
if(l1->val < l2->val){
newlist->next = l1;
l1 = l1->next;
}
else{
newlist->next = l2;
l2 = l2->next;
}
newlist = newlist->next;
}
//把剩下的部分接在新链表的尾部
newlist->next = l1? l1 : l2;
return head.next;
}
};
思路2
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0) return nullptr;
ListNode* ptr = lists[0];
while(lists.size() != 1){
ptr = mergeTwoLists(lists[0], lists[1]);
lists.erase(lists.begin());
lists.erase(lists.begin());
lists.push_back(ptr);
}
return ptr;
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
//给新链表一个不参与循环的头节点
ListNode head(-1);
ListNode *newlist = &head;
while(l1 && l2){
if(l1->val < l2->val){
newlist->next = l1;
l1 = l1->next;
}
else{
newlist->next = l2;
l2 = l2->next;
}
newlist = newlist->next;
}
//把剩下的部分接在新链表的尾部
newlist->next = l1? l1 : l2;
return head.next;
}
};