剑指 Offer II 025. 链表中的两数相加

给定两个 非空链表 l1和 l2 来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

可以假设除了数字 0 之外,这两个数字都不会以零开头。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) 
    {
        if( head== nullptr )
            return  head;
        if( head->next == nullptr)
            return head;
        ListNode* p = reverseList(head->next);
        head->next->next=head;
        head->next = nullptr;
        return  p;
    }

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 
    {
        if (l1==nullptr) 
        {
        return reverseList(l2);
        }
        if (l2==nullptr) 
        {
            return reverseList(l1);
        }
        ListNode* p=new ListNode;
        ListNode* Head=p;
        l1=reverseList(l1);
        l2=reverseList(l2);
        int sig=0;
        while(l1!=nullptr || l2!=nullptr || sig==1)
        {
            int temp=0;
            if(l1==nullptr && l2!=nullptr)
            {
                temp=l2->val+sig;
            }
            else if(l2==nullptr && l1!=nullptr)
            {
                temp=l1->val+sig;
            }
            else if(l1==nullptr && l2==nullptr && sig!=0)
            {
                temp=sig;
            }
            else
            {
                temp=l1->val+l2->val+ sig;
            }
            sig=0;
            if(temp>=10)
            {
                sig=1;
                temp=temp-10;
            }
            p->val=temp;
            if(l1!=nullptr)
            {
                l1=l1->next;
            }
            if(l2!=nullptr)
            {
                l2=l2->next;
            }
            if(l1!=nullptr || l2!=nullptr || sig==1)
            {    
                p->next=new ListNode;
                p=p->next;  
            }    
        }
        return reverseList(Head);
    }
};

// 字节面试题。去除链表翻转部分。

猜你喜欢

转载自blog.csdn.net/Doubao93/article/details/124185417