AcWing 36. 合并两个排序的链表
原题链接
简单
作者:
3_22
,
2024-11-14 22:31:44
,
所有人可见
,
阅读 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* head = new ListNode(-1);
ListNode* res = head;
while(l1 != NULL&&l2 != NULL){
if((l1->val)<(l2->val)){
head->next = l1;
l1 = l1->next;
}else{
head->next = l2;
l2 = l2->next;
}
head = head->next;
}
if(l1 != NULL){
head->next = l1;
}else{
head->next = l2;
}
return res->next;
}
};