Skip to content

Commit f6be63f

Browse files
committed
Add 2nd and 3rd codes
1 parent 38ee970 commit f6be63f

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

21/2.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
// always list1 <= list2
18+
if(list1->val > list2->val){
19+
swap(list1, list2);
20+
}
21+
22+
ListNode* ret = list1;
23+
list1 = list1->next;
24+
25+
ListNode *current = ret;
26+
27+
while(list1 != nullptr && list2 != nullptr){
28+
// always list1 <= list2
29+
if(list1->val > list2->val){
30+
swap(list1, list2);
31+
}
32+
33+
current->next = list1;
34+
list1 = list1->next;
35+
36+
current = current->next;
37+
}
38+
39+
if(list1 == nullptr){
40+
current->next = list2;
41+
return ret;
42+
}
43+
44+
if(list2 == nullptr){
45+
current->next = list1;
46+
return ret;
47+
}
48+
49+
return ret;
50+
}
51+
};

21/3.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
ListNode ret = ListNode();
15+
ListNode *current = &ret;
16+
17+
while(list1 != nullptr && list2 != nullptr){
18+
if(list1->val > list2->val){
19+
swap(list1, list2);
20+
}
21+
22+
current->next = list1;
23+
current = current->next;
24+
list1 = list1->next;
25+
}
26+
27+
if(list1 == nullptr){
28+
current->next = list2;
29+
}
30+
if(list2 == nullptr){
31+
current->next = list1;
32+
}
33+
34+
return ret.next;
35+
}
36+
};

0 commit comments

Comments
 (0)