题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: /** * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ ListNode* dz(ListNode* head){ if(head->next==nullptr){ return head; } ListNode *p=head; ListNode *f=head->next; ListNode *r=f->next; p->next=nullptr; while(r!=nullptr){ f->next=p; p=f; f=r; r=r->next; } f->next=p; return f; } ListNode* addInList(ListNode* head1, ListNode* head2) { if(head1==nullptr){ return head2; } if(head2==nullptr){ return head1; } ListNode *h1=dz(head1); ListNode *h2=dz(head2); int h=0; ListNode *ans=new ListNode(h1->val+h2->val); ListNode *a=ans; if(ans->val>9){ h=1; ans->val-=10; } h1=h1->next; h2=h2->next; while(h1!=nullptr&&h2!=nullptr){ ListNode *t=new ListNode(h1->val+h2->val+h); h=0; ans->next=t; ans=ans->next; if(ans->val>9){ h=1; ans->val-=10; } h1=h1->next; h2=h2->next; } while(h1!=nullptr){ ListNode *t=new ListNode(h1->val+h); h=0; ans->next=t; ans=ans->next; if(ans->val>9){ h=1; ans->val-=10; } h1=h1->next; } while(h2!=nullptr){ ListNode *t=new ListNode(h2->val+h); h=0; ans->next=t; ans=ans->next; if(ans->val>9){ h=1; ans->val-=10; } h2=h2->next; } if(h==1){ ListNode *t=new ListNode(h); h=0; ans->next=t; } ListNode *head=dz(a); return head; } };