两数相加||

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。

进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例:
输入:(7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 8 -> 0 -> 7

一种很烂的方法,将l1,l2翻转,每个结点加起来,得到的结果相翻转再返回。

struct ListNode* reverse(struct ListNode* head)
{
    if (head == NULL || head->next == NULL)
        return head;
    struct ListNode* before = NULL;
    struct ListNode* p = head;
    struct ListNode* later = p->next;
    while (p)
    {
        later = p->next;
        p->next = before;
        before = p;
        p = later;
    }
    return before;
}
struct ListNode *addTwoNumbers(struct ListNode *l1, struct ListNode *l2)
{
    struct ListNode *h1 = reverse(l1);
    struct ListNode *h2 = reverse(l2);
    struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode));
    head->next = NULL;
    struct ListNode *record = head;
    int flag = 0;
    while (h1 && h2)
    {
        struct ListNode *p = (struct ListNode*)malloc(sizeof(struct ListNode));
        p->val = h1->val + h2->val + flag;
        flag = p->val / 10;
        p->val %= 10;
        p->next = NULL;
        record->next = p;
        record = p;
        h1 = h1->next;
        h2 = h2->next;
    }
    while (h1)
    {
        h1->val += flag;
        flag = h1->val / 10;
        h1->val %= 10;
        record->next = h1;
        record = h1;
        h1 = h1->next;
    }
    while (h2)
    {
        h2->val += flag;
        flag = h2->val / 10;
        h2->val %= 10;
        record->next = h2;
        record = h2;
        h2 = h2->next;
    }
    if (flag)
    {
        head->val = 1;
        record->next = head;
        record = head->next;
        head->next = NULL;
        l1 = reverse(record);
    }
    else
        l1 = reverse(head->next);
    return l1;
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

你可能感兴趣的:(LeetCode,链表)