/**
* 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) {
l1=reverse(l1);
l2=reverse(l2);
ListNode* ahead=new ListNode(-1);
ListNode* p=ahead;
int c=0;
int val1,val2;
while(l1||l2)
{
val1=l1==NULL?0:l1->val;
val2=l2==NULL?0:l2->val;
p->next=new ListNode((val1+val2+c)%10);
p=p->next;
c=(val1+val2+c)/10;
l1=l1==NULL?NULL:l1->next;
l2=l2==NULL?NULL:l2->next;
}
if(c==1)
{
p->next=new ListNode(1);
}
return reverse(ahead->next);
}
ListNode* reverse(ListNode* head) {
ListNode* rhead=NULL;
ListNode* p=head;
ListNode* pre=NULL;
while(p)
{
ListNode* pnext=p->next;
if(pnext==NULL)rhead=p;
p->next=pre;
pre=p;
p=pnext;
}
return rhead;
}
};
大整数相加--链表结构正向存储--Add Two Numbers II
最新推荐文章于 2021-09-20 21:52:58 发布