Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
把所有数据放到一个数组里面排序,然后再根据结果生成新的链表。
//
// MergeKSortedLists.c
// Algorithms
//
// Created by TTc on 15/6/18.
// Copyright (c) 2015年 TTc. All rights reserved.
//
/**
* Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
把所有数据放到一个数组里面排序,然后再根据结果生成新的链表。
*/
#include "MergeKSortedLists.h"
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *
mergeTwoLists(struct ListNode *l1, struct ListNode *l2) {
if(l1==NULL&&l2==NULL) return NULL;
if(l1==NULL) return l2;
if(l2==NULL) return l1;
struct ListNode *newNode;
if(l1->val >= l2->val){
newNode = l2;
newNode->next = mergeTwoLists(l1, l2->next);
}else{
newNode=l1;
newNode->next = mergeTwoLists(l1->next, l2);
}
return newNode;
}
/**
* 双指针大法,创建两个 指针(首尾指针 向中间扫描)
*
*/
struct ListNode*
mergeKLists(struct ListNode** lists, int listsSize) {
int n = listsSize;
while(n >= 2){
for(int i = 0;i < n/2; i++){
lists[i] = mergeTwoLists(lists[i],lists[n-i-1]);
}
if(n%2==0) n=n/2;
else n=n/2+1;
}
return lists[0];
}