Skip to content

Commit f00a69e

Browse files
Update 21. Merge Two Sorted Lists.md
1 parent e1ce492 commit f00a69e

File tree

1 file changed

+52
-5
lines changed

1 file changed

+52
-5
lines changed

Linked List Problem/21. Merge Two Sorted Lists.md

Lines changed: 52 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,62 @@ Return <i>the head of the merged linked list.</i>
4040
```cpp
4141
class Solution {
4242
public:
43-
void deleteNode(ListNode* node) {
43+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
4444

45-
ListNode *nextNode = node->next;
45+
ListNode *merge, *tail;
4646

47-
swap(nextNode->val, node->val);
47+
if(list1 == NULL)
48+
{
49+
return list2;
50+
}
51+
if(list2 == NULL)
52+
{
53+
return list1;
54+
}
4855

49-
node->next = nextNode->next;
56+
if(list1->val < list2->val)
57+
{
58+
merge = list1;
59+
60+
list1 = list1->next;
61+
}
62+
else
63+
{
64+
merge = list2;
65+
66+
list2 = list2->next;
67+
}
5068

51-
delete(nextNode);
69+
tail = merge;
70+
71+
while(list1 != NULL && list2 != NULL)
72+
{
73+
if(list1->val < list2->val)
74+
{
75+
tail->next = list1;
76+
77+
list1 = list1->next;
78+
79+
tail = tail->next;
80+
}
81+
else
82+
{
83+
tail->next = list2;
84+
85+
list2 = list2->next;
86+
87+
tail = tail->next;
88+
}
89+
}
90+
if(list1 != NULL)
91+
{
92+
tail->next = list1;
93+
}
94+
if(list2 != NULL)
95+
{
96+
tail->next = list2;
97+
}
98+
return merge;
5299
}
53100
};
54101
```

0 commit comments

Comments
 (0)