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)
{
if(!l1) return l2;
if(!l2) return l1;
ListNode *p, *q;
ListNode *head = NULL;
ListNode *tail = NULL;
p = l1;
q = l2;
while(p&&q)
{
if(p->val < q->val)
{
if(!head)
{
head = p;
tail = p;
p = p->next;
}
else
{
tail->next = p;
p = p->next;
tail = tail->next;
}
}
else
{
if(!head)
{
head = q;
tail = q;
q = q->next;
}
else
{
tail->next = q;
q = q->next;
tail = tail->next;
}
}
}
if(!p)
{
tail->next = q;
}
if(!q)
{
tail->next = p;
}
return head;
}
};