Skip to content

Commit 2feccbe

Browse files
authored
LinkedList
1 parent c54a718 commit 2feccbe

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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 *head = NULL;
15+
if(list2 == NULL){
16+
return list1;
17+
}
18+
if(list1 == NULL){
19+
return list2;
20+
}
21+
if(list1->val <= list2->val){
22+
head = list1;
23+
list1 = list1->next;
24+
}
25+
else{
26+
head = list2;
27+
list2 = list2->next;
28+
}
29+
ListNode *curr = head;
30+
while(list1 != NULL && list2 != NULL ){
31+
if(list1->val <= list2->val){
32+
curr->next = list1;
33+
list1 = list1->next;
34+
}
35+
else{
36+
curr->next = list2;
37+
list2 = list2->next;
38+
}
39+
curr = curr->next;
40+
}
41+
if(list1){
42+
curr->next = list1;
43+
}
44+
else{
45+
curr->next = list2;
46+
}
47+
return head;
48+
49+
50+
}
51+
};
52+
53+
//Time: O(m+n)
54+
//Space: O(1)

0 commit comments

Comments
 (0)