題目描述
合併 k 個排序鏈表,返回合併後的排序鏈表。請分析和描述算法的複雜度。
示例:
輸入:
[
1->4->5,
1->3->4,
2->6
]
輸出: 1->1->2->3->4->4->5->6
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
白話題目:
算法:
詳細解釋關注 B站 【C語言全代碼】學渣帶你刷Leetcode 不走丟 https://www.bilibili.com/video/BV1C7411y7gB
C語言完全代碼
#include <stdio.h>
#include <stdlib.h>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#define MAX_SIZE 25
typedef struct ListNode
{
int val;
struct ListNode *next;
} ListNode;
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)); //整個頭指針方便處理
struct ListNode* tmp = head;
head -> next = NULL;
while(l1 != NULL && l2 != NULL)
{
if(l1 -> val <= l2 -> val)
{
tmp ->next = l1;
l1 = l1 -> next;
}
else
{
tmp ->next = l2;
l2 = l2 -> next;
}
tmp = tmp -> next;
}
if(l1 != NULL)
{
while(l1 != NULL)
{
tmp ->next = l1;
tmp = tmp -> next;
l1 = l1 -> next;
}
}
else if(l2 != NULL)
{
while(l2 != NULL)
{
tmp ->next = l2;
tmp = tmp -> next;
l2 = l2 -> next;
}
}
return head -> next;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize)
{
if(listsSize==0)
return NULL;
if(listsSize==1)
return lists[0];
struct ListNode*newhead=mergeTwoLists(lists[0],lists[1]);
int i;
for(i=2; i<listsSize; ++i)
{
newhead=mergeTwoLists(newhead,lists[i]);
}
return newhead;
}
ListNode *ListCreate(int n)
{
ListNode *p=NULL,*head,*r;
head=NULL;
r=head;
int i=0;
//尾插法
while(i<n)
{
int x;
scanf("%d",&x);
p=(ListNode*)malloc(sizeof(ListNode));
p->val=x;
if(head==NULL) //第一個
{
head=p;
r=p;
p->next=NULL;
}
else
{
r->next=p;
r=p;
}
i++;
}
r->next=NULL;
return head;
}
void ListPrint(struct ListNode *head)
{
ListNode *p;
p=head;
while(p!=NULL)
{
printf("%d ",p->val);
p=p->next;
}
printf("\n");
}
int main()
{
int listsSize;
printf("請輸入鏈表的個數\n");
scanf("%d",&listsSize);
int i;
struct ListNode** lists= (ListNode **)malloc(sizeof(ListNode *) * MAX_SIZE);
for(i=0; i<listsSize; i++)
{
printf("尾插法第%d個鏈表的元素個數\n",i+1);
int n;
scanf("%d",&n);
//ListNode * list=
lists[i] =ListCreate(n);//行的大小
// lists[i]=list;
}
printf("----------------------------\n");
for(i=0; i<listsSize; i++)
{
ListPrint(lists[i]);
printf("\n");
}
printf("----------------------------\n");
ListNode *result=mergeKLists(lists, listsSize);
ListPrint(result);
return 0;
}