avatar

剑指Offer-合并两个排序的链表

📝题目

1
2
3
4
5
6
7
8
9
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

示例1:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

限制:
0 <= 链表长度 <= 1000


📝思路

不是难题,但原来的写法比较绕,不够简洁,效率也稍微差点(条件语句太多),所以记录一下。

📝题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *res = new ListNode(0);
ListNode *cur = res;

while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
}
else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = (l1 == NULL ? l2 : l1);
return res->next;
}
Author:WhiteBeerHouse
Link:https://github.com/WhiteBeerHouse/WhiteBeerHouse.github.io/tree/master/2021/02/01/%E5%89%91%E6%8C%87Offer-%E5%90%88%E5%B9%B6%E4%B8%A4%E4%B8%AA%E6%8E%92%E5%BA%8F%E7%9A%84%E9%93%BE%E8%A1%A8/
Copyright Notice:All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.