Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
/**
* 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)
{
if(!l1)
return l2;
if(!l2)
return l1;
ListNode *head = new ListNode(0);
ListNode *p = l1, *q = l2;
ListNode *pp = head;
while(p && q)
{
if(p->val < q->val)
{
pp->next = p;
p = p->next;
pp = pp->next;
}
else
{
pp->next = q;
q = q->next;
pp = pp->next;
}
}
if(p)
pp->next = p;
if(q)
pp->next = q;
return head->next;
}
};