File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
LeetCode Blind 75 solutions Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
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)
You can’t perform that action at this time.
0 commit comments