#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node, *LinkedList;
// 创建一个新节点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Error! Unable to create a new node.\n");
exit(0);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表末尾添加新节点
void append(LinkedList* head, int data) {
if (*head == NULL) {
*head = createNode(data);
}
else {
Node* lastNode = *head;
while (lastNode->next != NULL) {
lastNode = lastNode->next;
}
lastNode->next = createNode(data);
}
}
// 打印链表
void printList(LinkedList head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
LinkedList mergeTwoLists(Node* head1, Node* head2)
{
if (head1 == NULL)
{
return head2;
}
if (head2 == NULL)
{
return head1;
}
Node *newList = NULL;
Node *curList = NULL;
newList = curList = (Node *)malloc(sizeof(Node));
while (head1 && head2)
{
if (head1->data > head2->data)
{
curList->next = head2;
head2 = head2->next;
}
else
{
curList->next = head1;
head1 = head1->next;
}
curList = curList->next;
}
if (head1)
{
curList->next = head1;
}
else
{
curList->next = head2;
}
Node* p = newList;
newList = newList->next;
free(p); //释放申请的空间
return newList;
}
LinkedList mergeKLists(Node** head, int k)
{
if (k == 0)
{
return NULL;
}
Node* newHead = head[0];
for (int i = 1; i < k; i++)
{
newHead = mergeTwoLists(newHead, head[i]);
}
return newHead;
}
int main() {
LinkedList head1 = NULL;
append(&head1, 1);
append(&head1, 3);
append(&head1, 5);
LinkedList head2 = NULL;
append(&head2, 1);
append(&head2, 3);
append(&head2, 6);
LinkedList head3 = NULL;
append(&head3, 2);
append(&head3, 4);
append(&head3, 6);
printf("Original List1: ");
printList(head1);
Node* lists[] = {head1, head2, head3};
LinkedList head = mergeKLists(lists, 3);
// 合并k个已排序的链表
printf("deleteDuplicate List: ");
printList(head);
system("pause");
return 0;
}
合并k个已排序的链表【C语言】
最新推荐文章于 2024-07-19 17:08:05 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)