|
| 1 | +#include <iostream> |
| 2 | +using namespace std; |
| 3 | +struct Node { |
| 4 | + int data; |
| 5 | + Node* next; |
| 6 | + Node(int val) : data(val), next(nullptr) {} |
| 7 | +}; |
| 8 | +Node* reverse(Node* head) { |
| 9 | + Node* prev = nullptr; |
| 10 | + Node* current = head; |
| 11 | + Node* next = nullptr; |
| 12 | + while (current != nullptr) { |
| 13 | + next = current->next; |
| 14 | + current->next = prev; |
| 15 | + prev = current; |
| 16 | + current = next; |
| 17 | + } |
| 18 | + return prev; |
| 19 | +} |
| 20 | +void insertAtTail(Node*& head, Node*& tail, int val) { |
| 21 | + Node* temp = new Node(val); |
| 22 | + if (head == nullptr) { |
| 23 | + head = temp; |
| 24 | + tail = temp; |
| 25 | + } else { |
| 26 | + tail->next = temp; |
| 27 | + tail = temp; |
| 28 | + } |
| 29 | +} |
| 30 | +Node* addTwoNumbers(Node* first, Node* second) { |
| 31 | + int carry = 0; |
| 32 | + Node* ansHead = nullptr; |
| 33 | + Node* ansTail = nullptr; |
| 34 | + while (first != nullptr || second != nullptr || carry != 0) { |
| 35 | + int val1 = (first != nullptr) ? first->data : 0; |
| 36 | + int val2 = (second != nullptr) ? second->data : 0; |
| 37 | + int sum = carry + val1 + val2; |
| 38 | + int digit = sum % 10; |
| 39 | + carry = sum / 10; |
| 40 | + insertAtTail(ansHead, ansTail, digit); |
| 41 | + if (first != nullptr) first = first->next; |
| 42 | + if (second != nullptr) second = second->next; |
| 43 | + } |
| 44 | + return ansHead; |
| 45 | +} |
| 46 | +Node* addTwoLists(Node* first, Node* second) { |
| 47 | + first = reverse(first); |
| 48 | + second = reverse(second); |
| 49 | + Node* ans = addTwoNumbers(first, second); |
| 50 | + ans = reverse(ans); |
| 51 | + return ans; |
| 52 | +} |
| 53 | +// Helper function to print list |
| 54 | +void printList(Node* head) { |
| 55 | + while (head != nullptr) { |
| 56 | + cout << head->data << " "; |
| 57 | + head = head->next; |
| 58 | + } |
| 59 | + cout << endl; |
| 60 | +} |
| 61 | +// Example usage |
| 62 | +int main() { |
| 63 | + Node* first = nullptr; |
| 64 | + Node* tail1 = nullptr; |
| 65 | + insertAtTail(first, tail1, 4); |
| 66 | + insertAtTail(first, tail1, 5); // Represents 45 |
| 67 | + Node* second = nullptr; |
| 68 | + Node* tail2 = nullptr; |
| 69 | + insertAtTail(second, tail2, 3); |
| 70 | + insertAtTail(second, tail2, 4); // Represents 34 |
| 71 | + Node* result = addTwoLists(first, second); |
| 72 | + printList(result); // Should print 7 9 for 79 |
| 73 | + return 0; |
| 74 | +} |
0 commit comments