AcWing 36. 合并两个排序的链表
原题链接
简单
作者:
古娜拉黑暗之神
,
2021-03-07 14:09:23
,
所有人可见
,
阅读 318
/**
* 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* cur_p = dummy; //cur_p为新链表的指针
while(l1!=0 && l2!=0){
if(l1->val > l2->val){
cur_p ->next = l2;
l2 = l2 ->next;
}else{
cur_p ->next= l1;
l1 = l1 ->next;
}
cur_p = cur_p->next;
}//这样结束的时候会至少有一个l1\l2会指向null
if(l1!=0) cur_p->next = l1;
if(l2!=0) cur_p->next = l2;
return dummy->next;
}
};