我试图将两个链表相乘,我使用了基本的数学乘法概念。拾取列表项将其与其他链接列表项相乘,并将结果存储到另一个链接列表中。我已经成功地实现了这样做,并且正确的乘法也存储在结果链表中。但是我在添加结果链表时面临问题。正确计算每一步的总和,但在最后一步,垃圾值替换总和。如果我的逻辑错误,请帮助我。
int multiply(struct node *first, struct node *second)
{
struct node *ans = NULL;
struct node *head = NULL;
struct node *rev_first = NULL;
struct node *rev_second = NULL;
int i, temp, mul, ten, carry=0, sum = 0;
rev_first = reverse(first);
rev_second = reverse(second);
while(rev_first != NULL)
{
ten = 1;
sum = 0;
head = rev_second;
while(head != NULL)
{
mul = (rev_first->data) * (head->data);
carry = mul / 10;
temp = mul % 10;
sum = sum + (temp * ten);
ten = ten * 10;
head = head->next;
}
push(&ans, sum);
rev_first = rev_first->next;
}
sum = 0;
head = reverse(ans);
for(mul = 1;head != NULL;(mul *= 10))
{
sum = sum + (mul * (head->data));
head = head->next;
}
return sum;
}
答案 0 :(得分:0)
我在您的代码中看到以下逻辑错误:
carry
循环开始之前将0
初始化为while
。carry
。carry
循环结束后使用while
。这是纠正后的功能。
int multiply(struct node *first, struct node *second)
{
struct node *ans = NULL;
struct node *head = NULL;
struct node *rev_first = NULL;
struct node *rev_second = NULL;
int i, temp, mul, ten, carry=0, sum = 0;
rev_first = reverse(first);
rev_second = reverse(second);
while(rev_first != NULL)
{
ten = 1;
carry = 0; // LINE ADDED
sum = 0;
head = rev_second;
while(head != NULL)
{
mul = (rev_first->data) * (head->data) + carry; // Added carry.
carry = mul / 10;
temp = mul % 10;
sum = sum + (temp * ten);
ten = ten * 10;
head = head->next;
}
// ADDED THIS IF BLOCK.
// If there is any carry, use it.
if ( carry > 0 )
{
sum += carry * ten;
}
push(&ans, sum);
printList(ans);
rev_first = rev_first->next;
}
sum = 0;
head = reverse(ans);
for(mul = 1;head != NULL;(mul *= 10))
{
sum = sum + (mul * (head->data));
head = head->next;
}
return sum;
}
<强> PS 强>
以下功能有助于追踪问题。
void printList(struct node* list)
{
for ( ; list != NULL; list = list->next )
{
printf("%d ", list->data);
}
printf("\n");
}