[leetcode] 21. merge two sorted lists

题目:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

标签:

Linked List

分析:

将两个有序列表合并为一个有序列表。为了减少逻辑判断,可以新建一个node作为虚拟头部,省去对原头部的单独处理。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class  {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

ListNode newhead(INT_MIN);
ListNode* tail = &newhead;
while (l1 != nullptr && l2 != nullptr) {
if (l1->val <= l2->val) {
tail->next = l1;
l1 = l1->next;
}
else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
// append the remaining list.
tail->next = l1 == nullptr? l2 : l1;
return newhead.next;
}
};