Skip to content

Instantly share code, notes, and snippets.

@mw-ding
Created April 29, 2012 08:25
Show Gist options
  • Save mw-ding/2545442 to your computer and use it in GitHub Desktop.
Save mw-ding/2545442 to your computer and use it in GitHub Desktop.
You have two numbers represented by a linked list, where each node contains a sin- gle 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
#include <iostream>
#include <boost/smart_ptr.hpp>
typedef struct node{
int value;
boost::shared_ptr<struct node> next;
}NODE;
boost::shared_ptr<NODE> Null = boost::shared_ptr<NODE>();
void printList(boost::shared_ptr<NODE> list){
if( list == Null )
return;
boost::shared_ptr<NODE> curr = list->next;
while( curr != Null ){
std::cout << curr->value << " -> ";
curr = curr->next;
}
std::cout << "NULL" << std::endl;
}
boost::shared_ptr<NODE> constructList(const int operand){
boost::shared_ptr<NODE> head = boost::shared_ptr<NODE>(new NODE);
boost::shared_ptr<NODE> curr = head;
int temp = operand;
while( temp >= 0 )
{
curr->next = boost::shared_ptr<NODE>(new NODE);
curr = curr->next;
curr->value = temp%10;
curr->next = Null;
temp = temp/10;
if( temp == 0 )
break;
}
return head;
}
boost::shared_ptr<NODE> sum(boost::shared_ptr<NODE> operand1, boost::shared_ptr<NODE> operand2)
{
boost::shared_ptr<NODE> result = boost::shared_ptr<NODE>(new NODE);
boost::shared_ptr<NODE> currResult = result;
boost::shared_ptr<NODE> currOp1 = operand1->next;
boost::shared_ptr<NODE> currOp2 = operand2->next;
int carry = 0;
int sum = 0;
while(currOp1 != Null || currOp2 != Null){
sum = 0;
if( currOp1 != Null ){
sum += currOp1->value;
currOp1 = currOp1->next;
}
if( currOp2 != Null ){
sum += currOp2->value;
currOp2 = currOp2->next;
}
sum += carry;
currResult->next = boost::shared_ptr<NODE>(new NODE);
currResult = currResult->next;
currResult->next = Null;
if( sum >= 10 ){
carry = 1;
sum = sum%10;
}else{
carry = 0;
}
currResult->value = sum;
}
return result;
}
int main(int argc, char *argv[])
{
int operand1, operand2;
std::cin >> operand1 >> operand2;
boost::shared_ptr<NODE> operandList1 = constructList(operand1);
std::cout << "Operand 1 is:" << std::endl;
printList(operandList1);
boost::shared_ptr<NODE> operandList2 = constructList(operand2);
std::cout << "Operand 2 is:" << std::endl;
printList(operandList2);
std::cout << "Result is:" << std::endl;
printList(sum(operandList1, operandList2));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment