Sum Lists

2.5 Sum Lists: You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1 's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

EXAMPLE
Input: (7-> 1 -> 6) + (5 -> 9 -> 2) .That is ,617 + 295.
Output: 2 -> 1 -> 9. That is, 912.

FOLLOW UP Suppose the digits are stored in forward order. Repeat the above problem.

EXAMPLE
Input: (6 -> 1 -> 7) + (2 -> 9 -> 5).Thatis,617 + 295.
Output: 9 -> 1 -> 2. That is, 912.
  • I chose to use strings because I didn't want to do the extra work of handling carries, or ensuring a new power digit, etc.

LinkedList* reverse_sum(Node *head1, Node *head2) {
    string int1 = "";
    string int2 = "";
    Node *iter = head1;
    while (iter) {
        int1.insert(0, to_string(iter->value));
        iter = iter->next;
    }
    iter = head2;
    while (iter) {
        int2.insert(0, to_string(iter->value));
        iter = iter->next;
    }

    int sum = atoi(int1.c_str()) + atoi(int2.c_str());
    int1 = to_string(sum);
    LinkedList *ll = new LinkedList();
    for (int i = int1.length() - 1; i >= 0; i--) {
        int digit = int1.at(i) - '0';
        ll->insert(digit);
    }
    return ll;
}


int main()
{
    LinkedList LL1;
    srand(time(nullptr));
    int counter = 0;
    int random;

    while (counter <= 5) {
        random = rand() % 10 + 2;
        LL1.insert(random);
        counter++;
    }
    LL1.print();

    counter = 0;
    LinkedList LL2;
    while (counter <= 3) {
        random = rand() % 10 + 2;
        LL2.insert(random);
        counter++;
    }

    LL2.print();
    LinkedList *LL3 = reverse_sum(LL1.front, LL2.front);
    LL3->print();
    pause();
}

Last updated