LeetCode 21 Merge Two Sorted Lists
#include <stddef.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* prehead = new ListNode(-1);
ListNode* begin = prehead;
while (l1 && l2){
if (l1->val < l2->val){
begin->next = l1;
l1 = l1->next;
}
else{
begin->next = l2;
l2 = l2->next;
}
begin = begin->next;
}
if (l1)
begin->next = l1;
else if (l2)
begin->next = l2;
return prehead->next;
}
};