LeetCode 2. 两数相加(C++)

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

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

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

C++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int getlen(ListNode* head)
    {
        int count=0;
        while(head)
        {
            count++;
            head=head->next;
        }
        return count;
    }
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 
    {
        int count1=getlen(l1);
        int count2=getlen(l2);
        ListNode* large;
        ListNode* small;
        if(count1>count2)
        {
            large=l1;
            small=l2;
        }
        else
        {
            large=l2;
            small=l1;
        }
        ListNode* p;
        int add=0;
        int num=large->val+small->val+add;
        if(num<10)
        {
            p=new ListNode(num);
            add=0;
        }
        else
        {
            p=new ListNode(num%10);
            add=num/10;
        }
        large=large->next;
        small=small->next;
        ListNode* head=p;
        while(small)
        {
            num=large->val+small->val+add;
            if(num<10)
            {
                p->next=new ListNode(num);
                add=0;
            }
            else
            {
                p->next=new ListNode(num%10);
                add=num/10;
            }
            p=p->next;
            small=small->next;
            large=large->next;
        }
        while(large)
        {
            num=large->val+add;
            if(num<10)
            {
                p->next=new ListNode(num);
                add=0;
            }
            else
            {
                p->next=new ListNode(num%10);
                add=num/10;
            }
            p=p->next;
            large=large->next;
        }
        if(add)
        {
            p->next=new ListNode(add);
        }
        return head;        
    }
};

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/85019671