This updated information has been further expanded upon on my new website. You can find the updated details here: https://k5kc.com/cs/algorithms/add-two-numbers-represented-as-linked-list-in-reversed-order/.
Problem
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.EXAMPLE
Input: (3 -> 1 -> 5) + (5 -> 9 -> 2)
Output: 8 -> 0 -> 8
INPUT: (2 -> 4 -> 3) + (5 -> 6 -> 4) (i.e. 342 + 465)
OUTPUT: 7 -> 0 -> 8 (i.e. 342 + 465 = 807)
Points to consider
- We should not forget the carry, especially when we have one more digit just for the carry. (e.g., 5 + 7 = 12, the ’1′ in 12 is due to the carry from last digit)
- Two numbers might not be of the same number of digits. (e.g., 7 + 3456 are 1 digit and 4 digit number)
- As the link list are reversed that of number, we have taken care of adding it from right to left i.e. least significant digit to most significant digit.
- digit1 and digit2 are neigher null
- digit1 is null
- digit2 is null
node *long_add(mynode *h1, mynode *h2, mynode *h3) //h3 = h2+h1 { node *c, *c1, *c2; int sum, carry, digit; carry = 0; c1 = h1->next; c2 = h2->next; while(c1 != h1 && c2 != h2) { sum = c1->value + c2->value + carry; digit = sum % 10; carry = sum / 10; h3 = insertNode(digit, h3); c1 = c1->next; c2 = c2->next; } if(c1 != h1) { c = c1; h = h1; } else { c = c2; h = h2; } while(c != h) { sum = c->value + carry; digit = sum % 10; carry = sum / 10; h3 = insertNode(digit, h3); c = c->next; } if(carry==1) { h3 = insertNode(carry, h3); } return(h3); }
Thanks.
More here - http://stackoverflow.com/questions/6960880/adding-two-linked-lists-efficiently-in-c
0 comments:
Post a Comment