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 *temp=new ListNode(-1),*p=l1,*q=l2,*pre;
pre=temp;
while(p&&q){
if(p->val>q->val) {temp->next=q;q=q->next;}
else{temp->next=p;p=p->next;}
temp=temp->next;
}
if(p) temp->next=p;
if(q) temp->next=q;
return pre->next;
}
};