Untitled
unknown
plain_text
2 years ago
3.1 kB
6
Indexable
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node {
int data;
struct Node* next;
struct Node* previous;
};
struct GiantInt {
struct Node* head;
struct Node* tail;
int size;
};
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
newNode->previous = NULL;
return newNode;
}
struct GiantInt* createGiantInt() {
struct GiantInt* newGiantInt = (struct GiantInt*)malloc(sizeof(struct GiantInt));
newGiantInt->head = NULL;
newGiantInt->tail = NULL;
newGiantInt->size = 0;
return newGiantInt;
}
void insertAtHead(struct GiantInt* giantInt, int value) {
struct Node* newNode = createNode(value);
if (giantInt->head == NULL) {
giantInt->head = giantInt->tail = newNode;
} else {
giantInt->head->previous = newNode;
newNode->next = giantInt->head;
giantInt->head = newNode;
}
giantInt->size++;
}
void insertAtTail(struct GiantInt* giantInt, int value) {
struct Node* newNode = createNode(value);
if (giantInt->tail == NULL) {
giantInt->head = giantInt->tail = newNode;
} else {
giantInt->tail->next = newNode;
newNode->previous = giantInt->tail;
giantInt->tail = newNode;
}
giantInt->size++;
}
void display(struct GiantInt* giantInt) {
struct Node* temp = giantInt->head;
while (temp != NULL) {
printf("%d", temp->data);
temp = temp->next;
}
}
void addition(struct GiantInt* result, struct GiantInt* a, struct GiantInt* b) {
int carry = 0, sum;
struct Node* a_curr = a->tail;
struct Node* b_curr = b->tail;
while (a_curr != NULL || b_curr != NULL) {
int a_val = (a_curr != NULL) ? a_curr->data : 0;
int b_val = (b_curr != NULL) ? b_curr->data : 0;
sum = a_val + b_val + carry;
carry = sum / 10;
sum %= 10;
insertAtHead(result, sum);
if (a_curr != NULL) a_curr = a_curr->previous;
if (b_curr != NULL) b_curr = b_curr->previous;
}
if (carry != 0) {
insertAtHead(result, carry);
}
}
void destroyGiantInt(struct GiantInt* giantInt) {
struct Node* current = giantInt->head;
while (current != NULL) {
struct Node* next = current->next;
free(current);
current = next;
}
free(giantInt);
}
int main() {
struct GiantInt* m = createGiantInt();
struct GiantInt* n = createGiantInt();
struct GiantInt* sum = createGiantInt();
string number1, number2;
cout << "Enter numbers to add: ";
cin >> number1 >> number2;
for (int i = 0; i < number1.length(); i++) {
insertAtTail(m, number1[i] - '0');
}
for (int i = 0; i < number2.length(); i++) {
insertAtTail(n, number2[i] - '0');
}
cout << "Sum: ";
addition(sum, m, n);
display(sum);
cout << endl;
destroyGiantInt(m);
destroyGiantInt(n);
destroyGiantInt(sum);
return 0;
}
Editor is loading...
Leave a Comment