Skip to content

Commit 4e66bda

Browse files
committed
add first solve code
1 parent 3046271 commit 4e66bda

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

21/1.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
14+
if(list1 == nullptr)return list2;
15+
if(list2 == nullptr)return list1;
16+
17+
ListNode *ret;
18+
if(list1->val < list2->val){
19+
ret = list1;
20+
list1 = list1->next;
21+
} else{
22+
ret = list2;
23+
list2 = list2->next;
24+
}
25+
ListNode *current = ret;
26+
27+
cout << current->val << endl;
28+
29+
while(list1 != nullptr || list2 != nullptr){
30+
if(list1 == nullptr){
31+
current->next = list2;
32+
return ret;
33+
}
34+
35+
if(list2 == nullptr){
36+
current->next = list1;
37+
return ret;
38+
}
39+
40+
if(list1->val < list2->val){
41+
current->next = list1;
42+
list1 = list1->next;
43+
}else{
44+
current->next = list2;
45+
list2 = list2->next;
46+
}
47+
current = current->next;
48+
}
49+
50+
return ret;
51+
}
52+
};

0 commit comments

Comments
 (0)