/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!l1) return l2;
if (!l2) return l1;
ListNode *head = NULL;
if (l1->val < l2->val) {
head = l1;
l1 = l1->next;
} else {
head = l2;
l2 = l2->next;
}
ListNode *node = head;
while (l1 && l2) {
if (l1->val < l2->val) {
node->next = l1;
node = l1;
l1 = l1->next;
} else {
node->next = l2;
node = l2;
l2 = l2->next;
}
}
if (l1) node->next = l1;
if (l2) node->next = l2;
return head;
}
};
Small Case: 4ms
Large Case: 60ms
Time: O(n)
Space: O(1)