/*
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-k-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize)
{
struct ListNode head = {0, NULL};
struct ListNode *p = &head;
do {
int j = -1;
for (int i = 0; i < listsSize; i++) {
if (lists[i] == NULL) {
continue;
} else if (j == -1) {
j = i;
continue;
}
if (lists[j]->val > lists[i]->val) {
j = i;
}
}
if (j == -1) {
break;
}
p->next = lists[j];
p = lists[j];
lists[j] = lists[j]->next;
}while(1);
return head.next;
}
static void output_link(const struct ListNode *link)
{
const struct ListNode *p = link;
while(p != NULL) {
printf("%d ", p->val);
p = p->next;
}
}
int main(void)
{
struct ListNode arr1[3] = {{1, NULL}, {4, NULL}, {5, NULL}};
struct ListNode arr2[3] = {{1, NULL}, {3, NULL}, {4, NULL}};
struct ListNode arr3[2] = {{2, NULL}, {6, NULL}};
struct ListNode *arr4[3];
arr1[0].next = &arr1[1];
arr1[1].next = &arr1[2];
arr2[0].next = &arr2[1];
arr2[1].next = &arr2[2];
arr3[0].next = &arr3[1];
arr4[0] = arr1;
arr4[1] = arr2;
arr4[2] = arr3;
struct ListNode *p = mergeKLists(arr4, 3);
output_link(p);
}
合并K个升序链表
最新推荐文章于 2024-05-15 17:25:40 发布