LeetCode(02AddTwoNumers)

LeetCode(02AddTwoNumers)

#include <iostream>
using namespace std;
/**

You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single digit.
Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

**/
//Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *l3 = new ListNode(0);
        ListNode *p = l1, *q = l2, *curr = l3;
        int carry = 0;
        while(p!=NULL || q!=NULL)
        {
            int x = (p != NULL) ? p->val : 0;
            int y = (q != NULL) ? q->val : 0;
            int sum = carry + x + y;
            carry = sum/10;
            curr->next = new ListNode(sum%10);
            curr = curr->next;
            if(p!=NULL)
            {
                p = p->next;
            }
            if(q!=NULL)
            {
                q = q->next;
            }
        }

        if(carry > 0)
        {
            curr->next = new ListNode(carry);
        }
        return l3->next;
    }
};

int main()
{
    ListNode* l1 = new ListNode(2);
    l1->next = new ListNode(4);
    l1->next->next = new ListNode(3);

    ListNode* l2 = new ListNode(5);
    l2->next = new ListNode(6);
    l2->next->next = new ListNode(4);

    ListNode* l3 = NULL;
    Solution solution;
    l3 = solution.addTwoNumbers(l1, l2);

    for(int i=0; i<3; i++)
    {
        cout << l3->val << " ";
        l3 = l3->next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36784975/article/details/85491860
02