合并k个升序链表
题目描述
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
第一种暴力解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int cmp(const void* a, const void* b){
return *(int*)a - *(int*)b;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){
//暴力输入可以将所有数值保存在数组中,然后将数组转换为链表
struct ListNode* head = NULL, *tail = NULL;
int arr[10000] = {0};
int k = 0;
for(int i = 0; i < listsSize; i++){
while(lists[i]){
arr[k++] = lists[i]->val;
lists[i] = lists[i]->next;
}
}
qsort(arr, k, sizeof(int), cmp);//排序函数,用cmp函数
for(int i = 0; i < k; i++){//创建新链表,将节点挂载到头部节点上
if(!head){
struct ListNode* p = malloc(sizeof(struct ListNode));
head = p;
tail = p;
p->val = arr[i];
p->next = NULL;
}else{
struct ListNode* p = malloc(sizeof(struct ListNode));
p->val = arr[i];
p->next = NULL;
tail->next = p;
tail = p;
}
}
return head;
}
第二种两两排序方式
```c
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode *l1, struct ListNode *l2){//两两排序
struct ListNode* head = malloc(sizeof(struct ListNode)), *tail = head;
//head.next = NULL;
while(l1 && l2){
if (l1->val <= l2->val){
tail->next = l1;
l1 = l1->next;
}
else{
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
tail->next = l1 ? l1 : l2;
return head->next;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){
//这里是直接想用两两比较然后插入,用自定义的merge函数
struct ListNode *l1, *l2;
if(!listsSize) return NULL;
l1 = lists[0];
for(int i = 1; i < listsSize; i++){
l2 = lists[i];
l1 = mergeTwoLists(l1, l2);
}
return l1;
}