題目描述
將兩個升序鏈表合併爲一個新的升序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
示例:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
白話題目:
兩個有序鏈表進行合併,還是升序排列。
算法:
(1)兩個鏈表輸入
(2)建立頭指針便於操作
(3)都不爲空的時候比較大小,小的放在前面,接到新的頭的位置;
(4)注意返回的是新鏈表的head->next
有一個爲空的時候,處理另外一個,順序都接到新鏈表上
詳細解釋關注 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;
* };
*/
typedef struct ListNode
{
int val;
struct ListNode *next;
} ListNode;
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");
}
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;
}
int main()
{
int l1Size,l2Size;
printf("輸入l1 l2節點個數\n");
scanf("%d %d",&l1Size,&l2Size);
ListNode *l1=ListCreate(l1Size);
ListNode *l2=ListCreate(l2Size);
ListNode *result=mergeTwoLists(l1, l2);
ListPrint(result);
return 0;
}