AcWing 36. 合并两个排序的链表
原题链接
简单
作者:
Sherry_
,
2019-06-24 13:54:11
,
所有人可见
,
阅读 763
算法1
注意最后直接挂新指针
C++ 代码
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode* dummy = new ListNode(0);
ListNode* head = dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
head->next = l1;
head = head->next;
l1 = l1->next;
}
else {
head->next = l2;
head = head->next;
l2 = l2->next;
}
}
head->next = l1 == NULL? l2 : l1;
// while (l1) {
// head->next = l1;
// head = head->next;
// l1 = l1->next;
// }
// while (l2) {
// head->next = l2;
// head = head->next;
// l2 = l2->next;
// }
return dummy->next;
}
};