LeetCode merge-two-sorted-lists

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 > 示例: > > 输入:1->2->4, 1->3->4 > 输出:1->1->2->3->4->4

解答:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode res {0};
ListNode *tmp = &res;

while (l1 && l2) {
if (l1->val <= l2->val) {
tmp->next = new ListNode{l1->val};
l1 = l1 ? l1->next : nullptr;
} else {
tmp->next = new ListNode{l2->val};
l2 = l2 ? l2->next : nullptr;
}
tmp = tmp->next;
}
if (l1) {
tmp->next = l1;
} else {
tmp->next = l2;
}
return res.next;
}
};

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×