#include <iostream>

class Node {
public:
    int data;
    Node* next;

    // Constructor to initialize a new node
    Node(int val) {
        data = val;
        next = nullptr;
    }
};

class fun {
public:
    void printN(Node* tmp);
    void addNo(Node* l1, Node* l2, Node*& res);
};

void fun::printN(Node* tmp) {
    while (tmp != nullptr) {
        std::cout << tmp->data << ' ';
        tmp = tmp->next;
    }
    std::cout << std::endl;
}

void fun::addNo(Node* l1, Node* l2, Node*& res) {
    Node* current = new Node(0);  // Dummy node to hold the result
    res = current;
    int carry = 0;

    while (l1 != nullptr || l2 != nullptr || carry != 0) {
        int sum = carry;

        if (l1 != nullptr) {
            sum += l1->data;
            l1 = l1->next;
        }

        if (l2 != nullptr) {
            sum += l2->data;
            l2 = l2->next;
        }

        carry = sum / 10; // Calculate carry
        current->next = new Node(sum % 10); // Create new node for the sum
        current = current->next; // Move to the next node
    }

    res = res->next; // Skip the dummy node and return the actual result
}

int main() {
    Node *a1, *a2, *a3;
    fun a;

    // First list: 1 -> 3 -> 5
    a1 = new Node(1);
    a2 = new Node(3);
    a3 = new Node(5);
    a1->next = a2;
    a2->next = a3;
    a3->next = nullptr;

    std::cout << "List 1: ";
    a.printN(a1);

    Node *b1, *b2, *b3;

    // Second list: 5 -> 3 -> 1
    b1 = new Node(5);
    b2 = new Node(3);
    b3 = new Node(1);
    b1->next = b2;
    b2->next = b3;
    b3->next = nullptr;

    std::cout << "List 2: ";
    a.printN(b1);

    Node* res = nullptr;
    a.addNo(a1, b1, res);

    std::cout << "Resulting sum list: ";
    a.printN(res); // This will print the resulting linked list after adding the two lists
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: