欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

2. 两数相加

程序员文章站 2022-04-17 15:51:30
...

2. 两数相加

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    int index1 = 1, index2 = 1;
    ListNode *temp1 = l1, *temp2 = l2;
    while (temp1->next != nullptr)
        index1++, temp1 = temp1->next;
    while (temp2->next != nullptr)
        index2++, temp2 = temp2->next;

    if (index1 > index2)
        //增加l2
        while (index1 > index2) {
            temp2->next = new ListNode(0);
            temp2 = temp2->next;
            index1--;
        }
    else if (index1 < index2)
        while (index1 < index2) {
            temp1->next = new ListNode(0);
            temp1 = temp1->next;
            index2--;
        }

    //各位相加进位
    temp1 = l1, temp2 = l2;
    auto *obj = new ListNode(-1);
    auto *nextTemp = obj;
    bool flag = false;
    while (temp1 != nullptr) {
        int value = temp1->val + temp2->val;
        if (flag)
            value++, flag = false;
        if (value >= 10)
            flag = true;
        nextTemp->next = new ListNode(value % 10);
        nextTemp = nextTemp->next;
        temp1 = temp1->next;
        temp2 = temp2->next;
    }
    if (flag)
        nextTemp->next = new ListNode(1);
    return obj->next;
}