AcWing 36. 合并两个排序的链表
原题链接
简单
作者:
深街酒徒
,
2024-11-30 20:55:23
,
所有人可见
,
阅读 1
/**
* 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 *m = l1; // 保留原链表
ListNode *n = l2;
ListNode *h = new ListNode(-1);
ListNode *p = h;
while(m != NULL && n != NULL)
{
if(m -> val < n -> val)
{
p -> next = m;
p = p -> next;
m = m -> next;
}
else
{
p -> next = n;
p = p -> next;
n = n -> next;
}
}
if(m != NULL) p -> next = m;
else p -> next = n;
return h -> next;
}
};