Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.2 kB
8
Indexable
Never
#include <iostream>
#include <string>

using namespace std;

struct Node {
    int data;
    Node* next;
    Node(int val) {
    data = val;
    next = nullptr;
}
};

Node* reverseList(Node* head) {
    Node* prev = nullptr;
    Node* current = head;
    Node* next = nullptr;
    while (current != nullptr) {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }
    return prev;
}

Node* addStrings(string s1, string s2) {
    Node* head1 = nullptr;
    Node* head2 = nullptr;

    // Create linked lists from the strings
    for (int i = s1.length() - 1; i >= 0; i--) {
        Node* newNode = new Node(s1[i] - '0');
        newNode->next = head1;
        head1 = newNode;
    }

    for (int i = s2.length() - 1; i >= 0; i--) {
        Node* newNode = new Node(s2[i] - '0');
        newNode->next = head2;
        head2 = newNode;
    }

    // Reverse both linked lists
    head1 = reverseList(head1);
    head2 = reverseList(head2);

    // Perform addition
    Node* resultHead = nullptr;
    Node* resultTail = nullptr;
    int carry = 0;
    Node* temp1 = head1;
    Node* temp2 = head2;
    while (temp1 || temp2 || carry) {
        int sum;
    if (temp1 && temp2) {
    sum = temp1->data + temp2->data + carry;
    } else if (temp1) {
    sum = temp1->data + carry;
    } else if (temp2) {
    sum = temp2->data + carry;
    } else {
    sum = carry;
    }
        carry = sum / 10;
        sum %= 10;
        Node* newNode = new Node(sum);
        if (!resultHead) {
            resultHead = newNode;
            resultTail = newNode;
        } else {
            resultTail->next = newNode;
            resultTail = newNode;
        }

        if (temp1) {
            temp1 = temp1->next;}
        if (temp2) {
            temp2 = temp2->next;}
    }

    // Reverse the result linked list
    resultHead = reverseList(resultHead);

    return resultHead;
}

void printList(Node* head) {
    while (head) {
        cout << head->data;
        head = head->next;
    }
    cout << endl;
}

int main() {
    string s1 = "119";
    string s2 = "82";

    Node* result = addStrings(s1, s2);

    cout << "Sum: ";
    printList(result);

    return 0;
}
Leave a Comment