2.Add Two Numbers

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 contains a single digit. Add the two numbers and return it as a linked list.

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

Solution:-

/**
 * 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 *addTwoNumbers(ListNode *l1, ListNode *l2)
    {
        if (l1 == NULL && l2 != NULL)
        {
            return l2;
        }
        if (l2 == NULL && l1 != NULL)
        {
            return l1;
        }
        if (l1 == NULL && l2 == NULL)
        {
            return l1;
        }

        ListNode *p = l1;
        ListNode *q = l2;
        ListNode *head = NULL;
        int res, carry = 0;
        ListNode *d = NULL;
        while (p != NULL && q != NULL)
        {
            res = (p->val + q->val + carry) % 10;
            carry = (p->val + q->val + carry) / 10;

            ListNode *temp = new ListNode;
            temp->next = NULL;
            temp->val = res;
            if (head == NULL)
            {
                head = temp;
                d = head;
            }
            else
            {
                d->next = temp;
                d = d->next;
            }

            p = p->next;
            q = q->next;
        }

        while (p != NULL)
        {
            res = (carry + p->val) % 10;
            carry = (carry + p->val) / 10;
            ListNode *temp = new ListNode;
            temp->next = NULL;
            temp->val = res;
            d->next = temp;
            d = d->next;
            p = p->next;
        }

        while (q != NULL)
        {
            res = (carry + q->val) % 10;
            carry = (carry + q->val) / 10;
            ListNode *temp = new ListNode;
            temp->next = NULL;
            temp->val = res;
            d->next = temp;
            d = d->next;
            q = q->next;
        }

        if (carry != 0)
        {
            ListNode *temp = new ListNode;
            temp->next = NULL;
            temp->val = carry;
            d->next = temp;
        }

        return head;
    }
};

Time Complexity:- O(n+m)

Last updated