Answer:
/**
* 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 *dummy=new ListNode(0);
dummy->next=l1;
ListNode *prev=dummy;
ListNode *p=l1;
ListNode *q=l2;
ListNode *qnext=NULL;
while(p&&q){
if(p->val<=q->val){
prev=p;
p=p->next;
}
else{
qnext=q->next;
prev->next=q;
q->next=p;
prev=q;
q=qnext;
}
}
if(q){
prev->next=q;
}
return dummy->next;
}
};
No comments:
Post a Comment