Untitled
#include <stdio.h> #include <stdlib.h> // Node structure for the linked list representing a number struct Node { int digit; struct Node* next; }; // Function to create a new node struct Node* createNode(int digit) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->digit = digit; newNode->next = NULL; return newNode; } // Function to insert a new node at the beginning of the linked list void insertAtBeginning(struct Node** head, int digit) { struct Node* newNode = createNode(digit); newNode->next = *head; *head = newNode; } // Function to add two numbers represented by linked lists struct Node* addNumbers(struct Node* num1, struct Node* num2) { struct Node* result = NULL; struct Node* temp = NULL; int carry = 0, sum; while (num1 != NULL || num2 != NULL || carry != 0) { sum = carry + (num1 ? num1->digit : 0) + (num2 ? num2->digit : 0); carry = sum / 10; sum = sum % 10; insertAtBeginning(&result, sum); if (num1) num1 = num1->next; if (num2) num2 = num2->next; } return result; } // Function to print a linked list representing a number void printNumber(struct Node* head) { struct Node* temp = head; while (temp != NULL) { printf("%d", temp->digit); temp = temp->next; } printf("\n"); } // Main function to test the addition of two large numbers using linked list int main() { // Example data for two large numbers represented by linked lists struct Node* num1 = NULL; struct Node* num2 = NULL; insertAtBeginning(&num1, 9); insertAtBeginning(&num1, 9); insertAtBeginning(&num1, 9); insertAtBeginning(&num2, 5); insertAtBeginning(&num2, 6); insertAtBeginning(&num2, 7); printf("Number 1: "); printNumber(num1); printf("Number 2: "); printNumber(num2); struct Node* result = addNumbers(num1, num2); printf("Sum: "); printNumber(result); return 0; } /* Number 1: 999 Number 2: 765 Sum: 1764 */
Leave a Comment