File tree 1 file changed +17
-46
lines changed
scripts/algorithms/M/Merge Two Sorted Lists
1 file changed +17
-46
lines changed Original file line number Diff line number Diff line change 1
- // 😉😉😉😉Please upvote if it helps 😉😉😉😉
1
+ // Runtime: 8 ms (Top 15.6%) | Memory: 15.10 MB (Top 46.21%)
2
+
2
3
class Solution {
3
4
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;
15
8
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 ;
38
16
}
39
- curr = curr -> next;
40
-
17
+ tail = tail->next ;
41
18
}
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 ;
51
22
}
52
- };
23
+ };
You can’t perform that action at this time.
0 commit comments