题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ struct ListNode* reverseList(struct ListNode* head) { struct ListNode *prev = NULL; struct ListNode *current = head; while (current != NULL) { struct ListNode *nextNode = current->next; current->next = prev; prev = current; current = nextNode; } return prev; } struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) { // write code here if(head1 == NULL) return head2; else if(head2 == NULL) return head1; head1=reverseList(head1); head2=reverseList(head2);//反转链表 struct ListNode *dummy = (struct ListNode*)malloc(sizeof(struct ListNode)); dummy->val = 0; dummy->next = NULL; struct ListNode *current = dummy; int carry=0; while(head1 != NULL || head2 != NULL || carry !=0) { int sum=carry; if(head1 != NULL) { sum +=head1->val; head1=head1->next; } if(head2 != NULL) { sum +=head2->val; head2=head2->next; } carry = sum/10; sum=sum%10; current->next = (struct ListNode*)malloc(sizeof(struct ListNode)); current->next->val = sum; current->next->next = NULL; current=current->next; } return reverseList(dummy->next); }