I am working on a single linked-list calculator in C (yes, it’s homework). I have the add functions “working” but for some reason I can only add two values that are the same length. I can’t really figure out how to add something like 12 + 128. Currently my code only accepts 120 + 128. What did I do wrong, how can I fix this code?
struct digit* add(struct digit *x, struct digit *y)
{
int carry = 0;
struct digit *xHead;
struct digit *yHead;
struct digit *totalHead;
struct digit *current_Digit;
xHead = x;
yHead = y;
totalHead = NULL;
while(x != NULL && y != NULL)
{
current_Digit = (struct digit *)malloc(sizeof(struct digit));
current_Digit->value = x->value + y->value + carry;
//calculates the carry
carry = 0;
if(current_Digit->value > 9)
{
carry = 1;
current_Digit->value = current_Digit->value % 10;
}
else
{
carry = 0;
}
current_Digit->next = totalHead;
totalHead = current_Digit;
x = x->next;
y = y->next;
}
return totalHead;
}
Instead of going to
x->nextandy->nextsimultaneously, your function should do the following:(It also looks as if you’re constructing your result list backwards…)