Skip to content

Instantly share code, notes, and snippets.

@yllan
Created May 16, 2022 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yllan/0e70e62ff85f6244230fb0082bd8609c to your computer and use it in GitHub Desktop.
Save yllan/0e70e62ff85f6244230fb0082bd8609c to your computer and use it in GitHub Desktop.
merge two lists
/**
* 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