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.
------------------------------------------
-----------------------------------------
Just merge two sorted lists into one sorted list. Nothing special.
/////////////////////////////////////////////////
//codes
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
//check
input
if (l1 == NULL)return l2;
if (l2 == NULL)return l1;
//dummy
node
ListNode*dum = new ListNode(-1), *pl1 = l1, *pl2 = l2, *p = dum;
while (pl1 != NULL && pl2 != NULL){
if
(pl1->val<pl2->val){
p->next = pl1;
p = p->next;
pl1 = pl1->next;
}
else{
p->next = pl2;
p = p->next;
pl2 = pl2->next;
}
}
//check
left nodes and connect to p
if (pl1 != NULL)p->next = pl1;
else p->next = pl2;
p = dum->next;
delete dum;
return p;
}
};
No comments:
Post a Comment