File tree Expand file tree Collapse file tree 1 file changed +52
-5
lines changed Expand file tree Collapse file tree 1 file changed +52
-5
lines changed Original file line number Diff line number Diff line change @@ -40,15 +40,62 @@ Return <i>the head of the merged linked list.</i>
40
40
``` cpp
41
41
class Solution {
42
42
public:
43
- void deleteNode (ListNode* node ) {
43
+ ListNode * mergeTwoLists (ListNode* list1, ListNode * list2 ) {
44
44
45
- ListNode * nextNode = node->next ;
45
+ ListNode * merge, * tail ;
46
46
47
- swap(nextNode->val, node->val);
47
+ if(list1 == NULL)
48
+ {
49
+ return list2;
50
+ }
51
+ if(list2 == NULL)
52
+ {
53
+ return list1;
54
+ }
48
55
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
+ }
50
68
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;
52
99
}
53
100
};
54
101
```
You can’t perform that action at this time.
0 commit comments