AcWing 36. 合并两个排序的链表
原题链接
简单
作者:
人生导师yxc
,
2023-01-03 22:57:57
,
所有人可见
,
阅读 117
合并两个排序的链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode* dummy = new ListNode(-1);//定义一个链表
ListNode* tail = dummy;//定义一个尾链表,使得dummy的next指针指向尾链表
while (l1 && l2)//循环条件:两个链表都没有走到头
{
if (l1 -> val < l2 -> val)//比较当前两个节点的值,较小的放在尾链表中
{
tail = tail -> next = l1;
l1 = l1 -> next;
}
else
{
tail = tail ->next = l2;
l2 = l2 -> next;
}
}
if (l1) tail -> next = l1;
if (l2) tail -> next = l2;
return dummy -> next;
}
};