key: judge if the lists end
Runtime: 8 ms / beats 73.38%
No reference
/**
* 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 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode *s1,*s2,*s3, res(0);
s1 = l1; s2 = l2; s3 = &res;
while(s1!=NULL && s2!=NULL)
{
if(s1->val < s2->val)
{
s3->next = s1;
s1 = s1->next;
}
else
{
s3->next = s2;
s2 = s2->next;
}
s3 = s3->next;
}
while(s1!=NULL)
{
s3->next = s1;
s1 = s1->next;
s3 = s3->next;
}
while(s2!=NULL)
{
s3->next = s2;
s2 = s2->next;
s3 = s3->next;
}
return res.next;
}
};