Leetcode#21 Merge two sorted lists
Published:
Link:
https://leetcode.com/problems/merge-two-sorted-lists/description/
Solution:
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head = NULL;
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
if(l1->val <= l2->val) {
head = l1;
l1 = l1->next;
} else {
head = l2;
l2 = l2->next;
}
ListNode* dummy_head = head;
while (l1 != NULL && l2 != NULL) {
if(l1->val <= l2->val) {
head->next = l1;
head = head->next;
l1 = l1->next;
}else{
head->next = l2;
head = head->next;
l2 = l2->next;
}
}
if (l1 != NULL) {
head->next = l1;
} else if (l2 != NULL) {
head->next =l2;
} else {
}
return dummy_head;
}
};