Reciprocal Linked List: Summation of Unbounded Numbers
Algorithm Title: Summing Unbounded Integers via Recursive Linked List Algorithm Algorithm: // a and b are pointers to the linked list representations of unbounded integers function add(node* a, node* b) //if either a or b are null, return the other if(a==null) then return b else if (b==null) then return a //create 3 node pointers: prev for the sum of the preceding digits, spot for the current digit, and result, which will store the sum node* prev = NULL; node* spot = NULL; node* result = NULL; //create carry variable to store carry of each sum as needed int carry = 0; //loop through a and b nodes until one of them reaches the end while (a != NULL || b != NULL) //create new node in spot spot = new Node(); //get the value of a, b and the previous carried value and sum them in this node spot->val = (a? a->val: 0) + (b? b->val: 0) + carry; //set the carry variable to equal one if the sum is greater than 10 carry = (spot->val >= 10)? 1 : 0; //if the sum is greater than 10, set the value to be the remainder of the sum divided by 10 if(spot->val >= 10) then spot->val = spot->val % 10 //if the result is null, set the result to the spot if (result == NULL) then result = spot; else prev->next = spot; //update prev to the spot prev = spot; //move the pointer on a or b to the next node if (a!=NULL) then a = a->next; if (b!=NULL) then b = b->next; //if the sum still has a carry at the end, set the next node of the spot pointer to be a new node which is equal to the carry if (carry == 1) then spot->next = new Node(); spot->next->val = carry; //return the result return result; end function References: Mukherjee, P. (2015). For unbounded integer addition, recursive linked list algorithm. Stack Abuse. Cont…