File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < iostream>
2+
3+ using namespace std ;
4+
5+ struct ListNode {
6+ int val;
7+ ListNode *next;
8+ ListNode () : val(0 ), next(nullptr ) {}
9+ ListNode (int x) : val(x), next(nullptr ) {}
10+ ListNode (int x, ListNode *next) : val(x), next(next) {}
11+ };
12+
13+ class Solution {
14+ public:
15+ ListNode* mergeTwoLists (ListNode* list1, ListNode* list2) {
16+ if (!list1)
17+ return (list2);
18+ if (!list2)
19+ return (list1);
20+
21+ ListNode ans_head = ListNode ();
22+ ListNode* tmp = &ans_head;
23+
24+ while (list1 && list2) {
25+ if (list1->val <= list2->val ) {
26+ tmp->next = list1;
27+ list1 = list1->next ;
28+ tmp = tmp->next ;
29+ }
30+ else {
31+ tmp->next = list2;
32+ list2 = list2->next ;
33+ tmp = tmp->next ;
34+ }
35+ }
36+ if (list1) {
37+ tmp->next = list1;
38+ }
39+ else if (list2) {
40+ tmp->next = list2;
41+ }
42+ return (ans_head.next );
43+ }
44+ };
You can’t perform that action at this time.
0 commit comments