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) {
ListNode *list = new ListNode(0);
ListNode *p, *q, *r;
p = l1; q = l2; r = list;
while (p&&q){
if (p->val <= q->val){
r->next = p;
p = p->next;
}
else {
r->next = q;
q = q->next;
}
r = r->next;
}//while
r->next = q ? q : p;
return list->next;
}
};