Skip to content

Commit f56482d

Browse files
committed
Runtime: 8 ms (Top 15.6%) | Memory: 15.10 MB (Top 46.21%)
1 parent 568d1bd commit f56482d

File tree

1 file changed

+17
-46
lines changed

1 file changed

+17
-46
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,23 @@
1-
// 😉😉😉😉Please upvote if it helps 😉😉😉😉
1+
// Runtime: 8 ms (Top 15.6%) | Memory: 15.10 MB (Top 46.21%)
2+
23
class Solution {
34
public:
4-
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
5-
6-
// if list1 happen to be NULL
7-
// we will simply return list2.
8-
if(list1 == NULL)
9-
return list2;
10-
11-
// if list2 happen to be NULL
12-
// we will simply return list1.
13-
if(list2 == NULL)
14-
return list1;
5+
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
6+
ListNode dummy(INT_MIN);
7+
ListNode *tail = &dummy;
158

16-
ListNode * ptr = list1;
17-
if(list1 -> val > list2 -> val)
18-
{
19-
ptr = list2;
20-
list2 = list2 -> next;
21-
}
22-
else
23-
{
24-
list1 = list1 -> next;
25-
}
26-
ListNode *curr = ptr;
27-
28-
// till one of the list doesn't reaches NULL
29-
while(list1 && list2)
30-
{
31-
if(list1 -> val < list2 -> val){
32-
curr->next = list1;
33-
list1 = list1 -> next;
34-
}
35-
else{
36-
curr->next = list2;
37-
list2 = list2 -> next;
9+
while (l1 && l2) {
10+
if (l1->val < l2->val) {
11+
tail->next = l1;
12+
l1 = l1->next;
13+
} else {
14+
tail->next = l2;
15+
l2 = l2->next;
3816
}
39-
curr = curr -> next;
40-
17+
tail = tail->next;
4118
}
42-
43-
// adding remaining elements of bigger list.
44-
if(!list1)
45-
curr -> next = list2;
46-
else
47-
curr -> next = list1;
48-
49-
return ptr;
50-
19+
20+
tail->next = l1 ? l1 : l2;
21+
return dummy.next;
5122
}
52-
};
23+
};

0 commit comments

Comments
 (0)