Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
/**
* 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* l1, ListNode* l2) {
ListNode *const head = new ListNode();
ListNode *current = head;
while (l1 != nullptr && l2 != nullptr) {
if (l1->val < l2->val) {
current->next = l1;
l1 = l1->next;
} else {
current->next = l2;
l2 = l2->next;
}
current = current->next;
}
if (l1 != nullptr) current->next = l1;
if (l2 != nullptr) current->next = l2;
return head->next;
}
};
/**
* 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* l1, ListNode* l2) {
ListNode *const head = new ListNode();
ListNode *current = head;
while (l1 != nullptr && l2 != nullptr) {
if (l1->val < l2->val) {
current->next = new ListNode(l1->val);
l1 = l1->next;
} else {
current->next = new ListNode(l2->val);
l2 = l2->next;
}
current = current->next;
}
while (l1 != nullptr) {
current->next = new ListNode(l1->val);
l1 = l1->next;
current = current->next;
}
while (l2 != nullptr) {
current->next = new ListNode(l2->val);
l2 = l2->next;
current = current->next;
}
return head->next;
}
};