题解 | #链表相加(二)#
链表相加(二)
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) {
if (head == NULL || head->next == NULL)
return head;
struct ListNode* new_head = NULL;
while (head != NULL) {
struct ListNode* next = head->next;
head->next = new_head;
new_head = head;
head = next;
}
return new_head;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2) {
// write code here
if (head1 == NULL && head2 == NULL)
return NULL;
struct ListNode* new_head1 = reverseList(head1);
struct ListNode* new_head2 = reverseList(head2);
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* res = dummy;
int carry = 0; // 进位
while (new_head1 != NULL || new_head2 != NULL) {
int sum = carry;
if (new_head1 != NULL) {
sum += new_head1->val;
new_head1 = new_head1->next;
}
if (new_head2 != NULL) {
sum += new_head2->val;
new_head2 = new_head2->next;
}
carry = sum / 10;
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = sum % 10;
node->next = NULL;
res->next = node;
res = res->next;
}
if (carry > 0) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = carry;
node->next = NULL;
res->next = node;
}
struct ListNode* new_head3 = reverseList(dummy->next);
return new_head3;
}
智元机器人成长空间 206人发布