Created
May 16, 2022 14:22
-
-
Save yllan/0e70e62ff85f6244230fb0082bd8609c to your computer and use it in GitHub Desktop.
merge two lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
ListNode *sentinel = new ListNode(); | |
ListNode *tail = sentinel; | |
while (list1 && list2) { | |
if (list1->val > list2->val) swap(list1, list2); | |
tail->next = list1; | |
tail = tail->next; | |
list1 = list1->next; | |
} | |
tail->next = list1 ? list1 : list2; | |
return sentinel->next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment