/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
if(l1 == NULL )
return l2;
if(l2 == NULL )
return l1;
if(l1 == NULL && l2 == NULL )
return NULL;
ListNode * head = NULL;
ListNode * preo = NULL;
int Y = 0;
while( l1 && l2 )
{
int tmp = l1->val + l2->val + Y;
Y=tmp/10;
int Val=tmp%10;
ListNode* Node = new ListNode(tmp);
Y= Node->val / 10;
Node->val %= 10;
if(head == NULL)
head = Node;
else
preo->next = Node;
preo = Node;
l1=l1->next;
l2=l2->next;
}
while(l1)
{
int tmp = l1->val+Y;
Y=tmp/10;
int Val = tmp%10;
ListNode* Node = new ListNode(Val);
if( head == NULL )
head = Node;
else
preo->next = Node;
preo = Node;
l1=l1->next;
}
while(l2)
{
int tmp = l2->val+Y;
Y=tmp/10;
int Val = tmp%10;
ListNode* Node = new ListNode(Val);
if( head == NULL )
head = Node;
else
preo->next = Node;
preo = Node;
l2=l2->next;
}
if(Y!=0)
{
ListNode* Node = new ListNode(1);
preo->next = Node;
}
return head;
}
};
感触: 有指针操作时一定要小心 = 和 == , 我好粗心啊..