AcWing 36. 合并两个排序的链表C++
原题链接
简单
作者:
沙漠绿洲
,
2020-08-19 20:59:30
,
所有人可见
,
阅读 460
C++ 代码
/**
* 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) {
if(!l1) return l2;
if(!l2) return l1;
ListNode* dummy = new ListNode(-1);
auto cur = dummy;
while(l1 && l2){
if(l1->val <= l2->val) cur->next = l1, l1 = l1->next;
else cur->next = l2, l2 = l2->next;
cur = cur->next;
}
if(l1) cur->next = l1;
if(l2) cur->next = l2;
return dummy->next;
}
};