题意:数的加法,因为数是翻转的,往后进位即可
思路:模拟,链表的过程,原来都是数组写,指针的写不习惯。。
/**
* 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) {
ListNode *head=new ListNode(0);
ListNode * nex=head;
int add=0;
while(l1||l2)
{
if(l1==NULL)
{
int x=l2->val+add;
add=x/10;
ListNode * p=new ListNode(x%10);
nex->next=p;
nex=p;
l2=l2->next;
}
else if(l2==NULL)
{
int x=l1->val+add;
add=x/10;
ListNode * p=new ListNode(x%10);
nex->next=p;
nex=p;
l1=l1->next;
}
else
{
int x=l1->val+l2->val+add;
add=x/10;
ListNode *p=new ListNode((x)%10);
nex->next=p;
nex=p;
l1=l1->next;
l2=l2->next;
}
}
if(add)
{
ListNode *p=new ListNode(add);
nex->next=p;
nex=p;
}
return head->next;
}
};