题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ #include <stdlib.h> struct ListNode* ReverseList(struct ListNode* head ) { // write code here struct ListNode* next = NULL; struct ListNode* prev = NULL; struct ListNode* curr = head; while (curr != NULL) { next = curr -> next; curr -> next = prev; prev = curr; curr = next; } return prev; } struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) { // write code here if (head1 == NULL) return head2; if (head2 == NULL) return head1; head1 = ReverseList(head1); head2 = ReverseList(head2); int temp = 0; struct ListNode* numList = malloc(sizeof(struct ListNode*)); struct ListNode* head = numList; int val1, val2, num; while (head1 != NULL || head2 != NULL || temp != 0) { val1 = head1 == NULL ? 0 : head1 -> val; val2 = head2 == NULL ? 0 : head2 -> val; num = val1 + val2 + temp; temp = num / 10; num %= 10; head -> next = malloc(sizeof(struct ListNode*)); head -> next -> val = num; head = head -> next; if (head1 != NULL) head1 = head1->next; if (head2 != NULL) head2 = head2->next; } return ReverseList(numList -> next); }