LeetCode_ Merge k Sorted Lists

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 *merge(ListNode *head1, ListNode * head2){ if(head1 == NULL) return head2;
if(head2 == NULL) return head1;
ListNode *head = new ListNode() ;
ListNode *p, *p1, *p2;
p = head, p1 = head1, p2 = head2;
while(p1 != NULL && p2 != NULL){
if(p1->val < p2->val){
p->next = p1;
p = p1;
p1 = p1->next;
}else{
p->next = p2;
p = p2;
p2 = p2->next;
}
}
p->next = p1 == NULL ? p2 : p1;
p = head->next; delete head;
return p;
}
ListNode *mergeKLists(vector<ListNode *> &lists) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = lists.size();
if(n < ) return NULL;
int len = ;
while(len < n){
for(int i = ; i + len < n; i += len * ){
lists[i] = merge(lists[i], lists[i+len]);
}
len = len<<;
}
return lists[];
}
};

归并的思路来做。

上一篇:Winform 串口通讯之读卡器


下一篇:Redis源代码分析(二十)--- ae事件驱动