Skip to content

Commit a01b06a

Browse files
Update 21.cpp
1 parent 07255ea commit a01b06a

File tree

1 file changed

+31
-18
lines changed

1 file changed

+31
-18
lines changed

leetcode/cpp/linkedlist/21.cpp

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,26 +13,39 @@
1313
class Solution {
1414
public:
1515
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;
2931
}
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;
3337
}
34-
mergedList=mergedList->next;
3538
}
39+
40+
if(curr1!=NULL)
41+
{
42+
prev->next=curr1;
43+
}
44+
if(curr2!=NULL)
45+
{
46+
prev->next=curr2;
47+
}
48+
3649
return head->next;
3750
}
38-
};
51+
};

0 commit comments

Comments
 (0)