在链表计算器中添加值
我正在用 C 语言开发一个单链表计算器(是的,这是家庭作业)。我有添加函数“工作”,但由于某种原因我只能添加两个长度相同的值。我真的不知道如何添加 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的函数不应同时转到
x->next
和y->next
,而是应执行以下操作:(它看起来也好像您正在构建结果向后列出...)
Instead of going to
x->next
andy->next
simultaneously, your function should do the following:(It also looks as if you're constructing your result list backwards...)
您当前正在递增两个参数的数字,而不查看是否已到达其中一个参数的末尾。您需要进行一项特殊测试,如果只有一个链表位于其末尾,则不要增加它并假设其数字值为零。
因此
12 + 128
应该动态地变为[0]12 + 128
。您必须添加逻辑来识别本例中的x
值已到达其数字末尾,但y
尚未到达。因此,继续使用y
并为x
数字变出零。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 thex
value in this case has reached the end of its digits but they
has not. So keep going with they
and conjure zero for thex
digit.您应该确保
x
和y
具有相同的位数,否则最终将设置为NULL
。在添加之前,找到最短的并添加零,直到匹配另一个的长度You should ensure
x
andy
have the same number of digits, otherwise you'll end up with either set toNULL
. Before adding, find the shortest and add zeros to it until you match the other's length