题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
struct ListNode* overturn(struct ListNode* head1){//翻转链表 struct ListNode* a1,*a2; a1=head1->next; a2=a1; if(a1->next){ a2=a1->next; } head1->next=NULL; while(head1!=a2){ a1->next=head1; head1=a1; a1=a2; if(a2->next!=NULL&&a2!=head1){ a2=a2->next; } } return head1; } /** * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) { if(head1==NULL){ return head2; } if(head2==NULL){ return head1; } struct ListNode* phead1,*phead2,*pphead=NULL,*HEAD; phead1=overturn(head1); phead2=overturn(head2); int NUM=0; while(phead1||phead2){ int num=0; if(phead1){ num+=phead1->val; phead1=phead1->next; } if(phead2){ num+=phead2->val; phead2=phead2->next; } NUM+=num; if(pphead==NULL){ HEAD=pphead=(struct ListNode*)malloc(sizeof(struct ListNode)); pphead->next=NULL; } else { pphead->next=(struct ListNode*)malloc(sizeof(struct ListNode)); pphead=pphead->next; pphead->next=NULL; } pphead->val=NUM%10; NUM/=10; } if(NUM){ pphead->next=(struct ListNode*)malloc(sizeof(struct ListNode)); pphead=pphead->next; pphead->next=NULL; pphead->val=NUM; } return overturn(HEAD); }