Untitled
unknown
plain_text
21 days ago
1.3 kB
4
Indexable
Never
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { cin.tie(nullptr)->sync_with_stdio(0); ListNode* dumyNode = new ListNode(0); ListNode* iterNode = dumyNode; while (list1 != nullptr && list2 != nullptr) { if (list1->val <= list2->val) { iterNode->next = list1; list1 = list1->next; } else { iterNode->next = list2; list2 = list2->next; } iterNode = iterNode->next; } while (list2 == nullptr && list1 != nullptr) { iterNode->next = list1; list1 = list1->next; iterNode = iterNode->next; } while (list1 == nullptr && list2 != nullptr) { iterNode->next = list2; list2 = list2->next; iterNode = iterNode->next; } return dumyNode->next; } };
Leave a Comment