Skip to content

Commit eef0996

Browse files
Improvement
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 4973627 commit eef0996

File tree

2 files changed

+12
-21
lines changed

2 files changed

+12
-21
lines changed

0021_merge_two_sorted_lists/merge_lists.c

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,25 +9,21 @@ struct ListNode {
99
static struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
1010
{
1111
struct ListNode dummy;
12-
struct ListNode *prev = &dummy;
12+
struct ListNode *tail = &dummy;
1313
dummy.next = l1;
1414

1515
while (l1 != NULL && l2 != NULL) {
1616
if (l1->val <= l2->val) {
17-
prev = l1;
17+
tail->next = l1;
1818
l1 = l1->next;
1919
} else {
20-
struct ListNode *tmp = l2->next;
21-
l2->next = l1;
22-
prev->next = l2;
23-
prev = l2;
24-
l2 = tmp;
20+
tail->next = l2;
21+
l2 = l2->next;
2522
}
23+
tail = tail->next;
2624
}
2725

28-
if (l2 != NULL) {
29-
prev->next = l2;
30-
}
26+
tail->next = l1 != NULL ? l1 : l2;
3127

3228
return dummy.next;
3329
}

0021_merge_two_sorted_lists/merge_lists.cc

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,26 +15,21 @@ using namespace std;
1515
class Solution {
1616
public:
1717
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
18-
struct ListNode *prev, dummy;
19-
20-
prev = &dummy;
18+
struct ListNode *tail, dummy;
19+
tail = &dummy;
2120
dummy.next = l1;
21+
2222
while (l1 != nullptr && l2 != nullptr) {
2323
if (l1->val <= l2->val) {
24-
prev = l1;
24+
tail->next = l1;
2525
l1 = l1->next;
2626
} else {
27-
struct ListNode *tmp = l2;
27+
tail->next = l2;
2828
l2 = l2->next;
29-
tmp->next = l1;
30-
prev->next = tmp;
31-
prev = tmp;
3229
}
3330
}
3431

35-
if (l2 != nullptr) {
36-
prev->next = l2;
37-
}
32+
tail->next = l1 != nullptr ? l1 : l2;
3833

3934
return dummy.next;
4035
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy