```/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param lists ListNode类一维数组
* @param listsLen int lists数组长度
* @return ListNode类
* Divide and Conquer
* 0 1 2 3 4 5 6 7 8;
* (0,1) (2,3) (4,5) (6,7) 8; divide;
* (0,1)->10 (2,3)->23 (4,5)->45 (6,7)->67 8->8;conquer;critical:0 1 return 10;
* 10 23 45 67 8 divide
* (10,23) (45,67) 8
* (10,23)->1023 (45,67)->4567 8->8;conquer;
* 1023 4567 8;
* (1023,4567) 8 ;divide;
* (1023,4567)->10234567 8->8 conquer
* (10234567,8) divide;
* (10234567,8)->102345678;
* finished;
*/
struct ListNode* merge2(struct ListNode* p, struct ListNode *q ) { // Conquer
struct ListNode *head, *tool, *headtrave, *Trav1, *Trav2;
Trav1 = p;
head = NULL;
headtrave = head;
Trav2 = q;
if(Trav1 == NULL && Trav2 == NULL) return NULL;
if(Trav1 != NULL && Trav2 == NULL) return Trav1;
if(Trav1 == NULL && Trav2 != NULL) return Trav2;
while(Trav1 && Trav2) {
if(Trav1->val >= Trav2->val) {
if(headtrave == NULL) {
headtrave = Trav2;
head = Trav2;
Trav2 = Trav2->next;
head->next = NULL;
} else {
tool = Trav2;
Trav2 = Trav2->next;
tool->next = headtrave->next;
headtrave->next = tool;
headtrave = tool;
}
} else {
if(headtrave == NULL) {
headtrave = Trav1;
head = Trav1;
Trav1 = Trav1->next;
head->next = NULL;
} else {
tool = Trav1;
Trav1 = Trav1->next;
tool->next = headtrave->next;
headtrave->next = tool;
headtrave = tool;
}
}
}
headtrave->next = Trav1?Trav1:Trav2;
return head;
}
struct ListNode* merge(struct ListNode** lists, int Left, int Right) { // Divide;
if(Left > Right) {
return NULL;
}
if(Left == Right) {
return lists[Left];
}
int Mid = (Left+Right)/2;
return merge2(merge(lists, Left, Mid), merge(lists, Mid+1, Right));
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) {
// write code here
if(listsLen == 0) {return NULL;}
if(listsLen == 1) {return lists[0];}
return merge(lists,0,listsLen-1);
}