开发者

Adding values in Linked-List Calculator

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
        {
            c开发者_高级运维arry = 0;
        }
        current_Digit->next = totalHead;
        totalHead = current_Digit;

        x = x->next;
        y = y->next;
    }
    return totalHead;
}


Instead of going to x->next and y->next simultaneously, your function should do the following:

while (x != NULL || y != NULL) {
    // malloc

    current_Digit->value = (x ? x->value : 0)
                         + (y ? y->value : 0)
                         + carry;

    // compute

    if (x) x = x->next;
    if (y) y = y->next;
}

(It also looks as if you're constructing your result list backwards...)


You're currently incrementing the digits of both arguments without looking at whether you've hit the end of one of them. You need to have a special test that if only one linked list is at its end, then don't increment it and just assume its digit value is zero.

So 12 + 128 should be dynamically made as [0]12 + 128. You must add logic to recognize that the x value in this case has reached the end of its digits but the y has not. So keep going with the y and conjure zero for the x digit.


You should ensure x and y have the same number of digits, otherwise you'll end up with either set to NULL. Before adding, find the shortest and add zeros to it until you match the other's length

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜