题解 | #链表相加(二)#
链表相加(二)
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, int* l) {
if (head == NULL) return NULL;
struct ListNode* p = NULL;
struct ListNode* c = head;
while (c != NULL) {
struct ListNode* n = c->next;
c->next = p;
p = c;
c = n;
(*l)++;
}
return p;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
// write code here
if (head1 == NULL) return head2;
if (head2 == NULL) return head1;
int l1 = 0, l2 = 0;
struct ListNode* r1 = reverseList(head1, &l1);
struct ListNode* r2 = reverseList(head2, &l2);
// printf("length of l1 %d\nlength of l2 %d\n", l1, l2);
if (l2 > l1) {
struct ListNode* t = r2;
r2 = r1;
r1 = t;
int tl = l2;
l2 = l1;
l1 = tl;
}
struct ListNode* head = r1;
int carry = 0;
while (l2 > 0) {
int sum = r1->val + r2->val + carry;
if (sum >= 10) {
sum -= 10;
carry = 1;
} else {
carry = 0;
}
r1->val = sum;
r1 = r1->next;
r2 = r2->next;
l2--;
l1--;
}
// printf("test\n");
while (l1 > 0) {
int sum = r1->val + carry;
if (sum >= 10) {
sum -= 10;
carry = 1;
} else {
carry = 0;
}
r1->val = sum;
if(l1 == 1) {
if(carry == 1) {
struct ListNode* one = malloc(sizeof(struct ListNode));
one->val = 1;
one->next = NULL;
r1->next = one;
}
}
r1 = r1->next;
l1--;
}
r1 = reverseList(head, &l1);
return r1;
}

