在链接列表计算器中添加值

| 我正在使用C语言开发单个链接列表计算器(是的,这是家庭作业)。我有添加函数\“ working \”,但是由于某种原因,我只能添加两个长度相同的值。我真的不知道如何添加类似12 + 128的内容。目前我的代码只接受120 +128。我做错了什么,如何解决此代码?
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;
}
    
已邀请:
您的函数应该执行以下操作,而不是同时转到
x->next
y->next
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;
}
(看起来好像您正在向后构造结果列表...)     
您当前正在递增两个参数的位数,而无需查看您是否已经达到了其中一个的结尾。您需要进行一次特殊的测试,如果只有一个链表在末尾,则不要对其进行递增,而只需假设其数字值为零即可。 因此,
12 + 128
应动态地设为as5ѭ。您必须添加逻辑以识别在这种情况下,
x
值已达到其数字的末尾,而but7ѭ尚未达到。因此继续使用with7ѭ,并为zero6ѭ数字改零。     
您应确保
x
y
的位数相同,否则最终将两者都设置为
NULL
。在添加之前,找到最短的并添加零,直到匹配另一个的长度     

要回复问题请先登录注册