https://leetcode.cn/problems/lMSNwu/
分别把给定的两个链表翻转,然后从头开始相加。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//反转链表
struct ListNode* reverselist(struct ListNode*h1)
{
struct ListNode* newhead = NULL;
struct ListNode* cur = h1;
while(cur)
{
struct ListNode* next = cur->next;
cur->next = newhead;
newhead = cur;
cur = next;
}
return newhead;
}
struct ListNode* add(struct ListNode*head1 , struct ListNode* head2)
{
//返回的新链表的头和尾
struct ListNode* head = NULL,* tail = NULL;
//进位
int carry = 0;
while(head1 || head2)
{
int n1 = head1? head1->val : 0;
int n2 = head2? head2->val : 0;
int sum = n1 + n2 + carry;
if(head == NULL)
{
head = tail = (struct ListNode*)malloc(sizeof(struct ListNode));
tail->val = sum % 10;
tail->next = NULL;
}
else
{
tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail->next->val = sum % 10;
tail = tail->next;
tail->next = NULL;
}
carry = sum / 10;
if(head1)
{
head1 = head1->next;
}
if(head2)
{
head2 = head2->next;
}
}
if(carry > 0)
{
tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));
tail->next->val = carry;
tail = tail->next;
tail->next = NULL;
}
return head;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
l1 = reverselist(l1);
l2 = reverselist(l2);
struct ListNode* l3 = add(l1,l2);
return reverselist(l3);
}