class Solution { public: ListNode* ReverseList(ListNode* head) { ListNode* cur=head; ListNode* pre=NULL; if(head==NULL) {return head;} while(cur!=NULL) { ListNode* tmp=cur->next; cur->next=pre; pre=cur; cur=tmp; } return pre; } ListNode* addInList(ListNode* head1, ListNode* head2) { if(head1==nullptr) return head2; if(head2==nullptr) return head1; //反转两个链表 head1=ReverseList(head1); head2=ReverseList(head2); ListNode* head=new ListNode(-1); ListNode* ptr=head; int tmp=0; while(head1!=nullptr||head2!=nullptr) { int val=tmp; if(head1!=nullptr) { val+=head1->val; head1=head1->next; } if(head2!=nullptr) { val+=head2->val; head2=head2->next; } //算出进位 tmp=val/10; //算出余位 ptr->next=new ListNode(val%10); ptr=ptr->next; } //链表加完后,注意最后一次的进位 if(tmp>0) { ptr->next=new ListNode(tmp); } return ReverseList(head->next); } };
核心:1.将两个链表倒置,这样可以保证可以从头加起;
2.创建储存和的链表,处理顺序:计算位和->计算进位->储存进位->计算余位->用节点储存余位