0%

two-sorted-lists

Merge Two Sorted Lists – LeetCode 21

Problem

Description

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.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if((l1 == nullptr) && (l2 == nullptr)) return nullptr;
ListNode *dummyRoot = new ListNode(0);
ListNode *ptr = dummyRoot;
while((l1 != nullptr) || (l2 != nullptr)){
if(l1 == nullptr) {ptr->next = new ListNode(l2->val); ptr = ptr->next; l2 = l2->next; continue;}
if(l2 == nullptr) {ptr->next = new ListNode(l1->val); ptr = ptr->next; l1 = l1->next; continue;}
if(l1->val < l2->val) {ptr->next = new ListNode(l1->val); ptr = ptr->next; l1 = l1->next;}
else {ptr->next = new ListNode(l2->val); ptr = ptr->next; l2 = l2->next;}
}
ptr = dummyRoot->next;
delete dummyRoot;
return ptr;
}
};

思路

要求合并两个已排序的List,没有难度,单纯的遍历拼接,只需注意DummyRoot的处理就行了。不过事后看了不少答案都倾向复用参数已有的ListNode部分。我认为这个函数不应该引用原有的l1和l2,因为可能会因此造成潜在的问题,比如资源的不正确访问和释放。时间复杂度是$O(m + n)$,m和n分别为两个List的长度,空间复杂度是$O(1)$。
耗时$9$ ms,排名$38.42\%$。

Better

思路

另外的思路是递归解,就算了。