合并 k 个升序的链表并将结果作为一个升序的链表返回其头节点。
#include <stdio.h>
#include <stdlib.h>
typedef int data_t;
typedef struct ListNode{
data_t val;
struct ListNode *next;
}node_t;
node_t *merge(node_t *phead1, node_t *phead2){
node_t *cur = (node_t *) malloc(sizeof(node_t));
cur->next = NULL;
node_t *res = cur;
if(phead1->next == NULL){
cur = phead2;
return cur;
}
if(phead2->next == NULL){
cur = phead1;
return cur;
}
phead1 = phead1->next;
phead2 = phead2->next;
while (phead1 != NULL && phead2 != NULL){
if(phead1->val <= phead2->val){
cur->next = phead1;
cur = cur->next;
phead1 = phead1->next;
} else{
cur->next = phead2;
cur = cur->next;
phead2 = phead2->next;
}
}
if(phead1 != NULL){
cur->next = phead1;
}
if(phead2 != NULL){
cur->next = phead2;
}
return res;
}
node_t *merge_list(node_t **list, int num){
for (int i = 1; i < num; ++i) {
list[0] = merge(list[0], list[i]);
}
return list[0];
}
//节点插入
void node_insert(struct ListNode* head, data_t x){
struct ListNode* node = (struct ListNode*) malloc(sizeof(struct ListNode));
node->val = x;
while (head->next != NULL){
head = head->next;
}
node->next = head->next;
head->next = node;
}
/**
* 递增链表创建
* @param start 起始大小
* @param num 链表长度
* @return
*/
struct ListNode* list_create(int start, int num){
struct ListNode* list = (struct ListNode*) malloc(sizeof(struct ListNode));
list->next = NULL;
for (int i = 0; i < num; ++i) {
node_insert(list,i+start);
}
return list;
}
int main(){
node_t *list1 = list_create(1,2);
node_t *list2 = list_create(2,0);
node_t *list3 = list_create(1,1);
node_t *list4 = list_create(5,4);
node_t *list[4] = {list1,list2,list3,list4};
node_t *res = merge_list(list,4);
while (res->next != NULL){
printf("%d ",res->next->val);
res = res->next;
}
printf("\n");
return 0;
}