File tree Expand file tree Collapse file tree 1 file changed +31
-18
lines changed Expand file tree Collapse file tree 1 file changed +31
-18
lines changed Original file line number Diff line number Diff line change 13
13
class Solution {
14
14
public:
15
15
ListNode* mergeTwoLists (ListNode* l1, ListNode* l2) {
16
- if (!l1 && !l2) return l1;
17
- if (!l1 && l2) return l2;
18
- if (!l2 && l1) return l1;
19
- ListNode *mergedList,*head;
20
- int x,y;
21
- mergedList=new ListNode (0 );
22
- head=mergedList;
23
- while (l1 || l2){
24
- x=l1? l1->val : INT_MAX;
25
- y=l2? l2->val : INT_MAX;
26
- if (l1 && x<=y){
27
- mergedList->next =new ListNode (x);
28
- l1=l1->next ;
16
+ if (l1==NULL || l2==NULL )
17
+ return l1==NULL ?l2:l1;
18
+ ListNode* head=new ListNode (-1 );
19
+ ListNode* prev=head;
20
+
21
+ ListNode* curr1=l1;
22
+ ListNode* curr2=l2;
23
+
24
+ while (curr1!=NULL && curr2!=NULL )
25
+ {
26
+ if (curr1->val <=curr2->val )
27
+ {
28
+ prev->next =curr1;
29
+ prev=curr1;
30
+ curr1=curr1->next ;
29
31
}
30
- else if (l2){
31
- mergedList->next =new ListNode (y);
32
- l2=l2->next ;
32
+ else
33
+ {
34
+ prev->next =curr2;
35
+ prev=curr2;
36
+ curr2=curr2->next ;
33
37
}
34
- mergedList=mergedList->next ;
35
38
}
39
+
40
+ if (curr1!=NULL )
41
+ {
42
+ prev->next =curr1;
43
+ }
44
+ if (curr2!=NULL )
45
+ {
46
+ prev->next =curr2;
47
+ }
48
+
36
49
return head->next ;
37
50
}
38
- };
51
+ };
You can’t perform that action at this time.
0 commit comments