两个有序链表合并
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode * p1 = l1;
ListNode * p2 = l2;
ListNode * l3= NULL;
if(l1==NULL && l2==NULL)
return l3;
else if( l1 != NULL && l2== NULL)
{
return l1;
}
else if( l1 == NULL && l2 != NULL)
{
return l2;
}
if( l1!=NULL && l2 != NULL )
{
if( l1->val <= l2->val )
{
l3=l1;
p1= p1->next;
}
else
{
l3=l2;
p2=p2->next;
}
}
ListNode *p=l3;
while( p1 != NULL && p2 != NULL )
{
if( p1->val <= p2->val)
{
if(p->next == p1)
{
p=p->next;
l1=p;
p1= p1->next;
}
else
{
l1=p1->next;
p->next = p1;
p1->next = p2;
p=p1;
p1=l1;
}
}
else
{
if(p->next == p2 )
{
p=p->next;
l2=p;
p2=p2->next;
}
else
{
l2=p2->next;
p->next = p2;
p2->next = p1;
p=p2;
p2=l2;
}
}
}
if(p1==NULL)
{
p->next=p2;
}
if(p2==NULL)
{
p->next = p1;
}
return l3;
}
};