题解 | #链表相加(二)#
链表相加(二)
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) { // write code here if (head == NULL || head->next == NULL) return head; struct ListNode* pre = NULL; struct ListNode* mid = head; struct ListNode* next = NULL; while (mid != NULL) { next = mid->next; mid->next = pre; pre = mid; mid = next; } return pre; } struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) { // write code here if (head1 == NULL && head2 != NULL) { return head2; } if (head2 == NULL && head1 != NULL) { return head1; } head1 = ReverseList(head1); head2 = ReverseList(head2); int flag = 0; struct ListNode* temp = (struct ListNode*) malloc(sizeof(struct ListNode)); temp->next = NULL; struct ListNode* pre = temp; int value = 0; int val1 = 0; int val2 = 0; while (head2 != NULL || head1 != NULL||flag==1) { val1 = head1 == NULL ? 0 : head1->val; val2 = head2 == NULL ? 0 : head2->val; value = val1 + val2 + flag; struct ListNode* node = (struct ListNode*) malloc(sizeof(struct ListNode)); node->next = NULL; if (value >= 10) { flag = 1; value = value % 10; node->val = value; pre->next = node; } else { flag = 0; node->val = value; pre->next = node; } pre = pre->next; if (head1 != NULL) { head1 = head1->next; } if (head2 != NULL) { head2 = head2->next; } } struct ListNode* dummy = temp->next; free(temp); return ReverseList(dummy); }