/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* setDummyHead(struct ListNode* l)
{
struct ListNode* dummyHead = malloc(sizeof(struct ListNode));
dummyHead->val = 0;
dummyHead->next = l;
return dummyHead;
}
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode* head;
struct ListNode* l;
l1 = setDummyHead(l1);
l2 = setDummyHead(l2);
head = l1;
l = l1;
l1 = l1->next;
l2 = l2->next;
while (l1 != NULL && l2 != NULL)
{
if (l1->val < l2->val)
{
l->next = l1;
l1 = l1->next;
}
else
{
l->next = l2;
l2 = l2->next;
}
l = l->next;
}
while (l2 != NULL)
{
l->next = l2;
l2 = l2->next;
l = l->next;
}
while (l1 != NULL)
{
l->next = l1;
l1 = l1->next;
l = l->next;
}
return head->next;
}
参考:
leetcode - 21. Merge Two Sorted Lists