c-两个链表相乘时的输出错误



我正在尝试将两个链表相乘,并且我已经使用了基本的数学乘法概念。拾取一个列表项乘以其他链表项,并将结果存储到另一个链表中。我已经成功地做到了这一点,正确的乘法也存储在结果链表中。但我在添加结果链接列表时遇到了问题。每一步的总和都是正确计算的,但在最后一步,垃圾值会替换总和。如果我的逻辑错了,请帮帮我。

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;
}

我在您的代码中看到以下逻辑错误:

  1. 您忘记在内部while循环开始之前将carry初始化为0
  2. 使用乘法计算项时,您忘记使用carry
  3. 您忘记在内部while循环结束后使用carry

这是修正后的函数。

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");
}

相关内容

  • 没有找到相关文章

最新更新