#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL)
{
return l2;
}
else if (l2 == NULL)
{
return l1;
}
struct ListNode* ans = NULL;
struct ListNode* p = NULL;
struct ListNode* q = NULL;
int f = 0;
while (l1 != NULL && l2 != NULL)
{
p = (struct ListNode*)malloc(sizeof(struct ListNode));
p->next = NULL;
if (l1->val < l2->val)
{
p->val = l1->val;
l1 = l1->next;
}
else
{
p->val = l2->val;
l2 = l2->next;
}
if (f == 1)
{
q->next = p;
q = q->next;
}
else if (f == 0)
{
f = 1;
ans = p;
q = p;
}
}
if (l1 == NULL && l2 == NULL)
{
return ans;
}
struct ListNode* t;
if (l1 == NULL)
{
t = l2;
}
else if (l2 == NULL)
{
t = l1;
}
while (t != NULL)
{
p = (struct ListNode*)malloc(sizeof(struct ListNode));
p->next = NULL;
p->val = t->val;
t = t->next;
q->next = p;
q = q->next;
}
return ans;
}
LeetCode21. 合并两个有序链表
最新推荐文章于 2022-10-23 21:15:00 发布