263.LeetCode | 21. 合并两个有序链表
每天一个开发小知识
01
将两个升序链表合并为一个新的升序链表并返回
新链表是通过拼接给定的两个链表的所有节点组成的
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode * dummy = new ListNode();
ListNode * p = dummy;
ListNode * q = l1;
ListNode * f = l2;
while (NULL != q || NULL != f)
{
if (NULL != q && NULL != f)
{
if (q->val < f->val)
{
p->next = q;
p = p->next;
q = q->next;
}
else
{
p->next = f;
p = p->next;
f = f->next;
}
}
else if (NULL != q)
{
p->next = q;
p = p->next;
q = q->next;
}
else
{
p->next = f;
p = p->next;
f = f->next;
}
}
return dummy->next;
}
};