【问题标题】:C sum of Squares from linked list链表中的 C 平方和
【发布时间】:2021-02-27 02:56:13
【问题描述】:

您好,我正在尝试制作一个程序,该程序采用整数链表并对 int 的平方求和,使用递归。到目前为止我已经尝试过了,但是我无法让平方和的功能起作用。我不知道使用 pow() 是否是最好的方法?

#include <stdio.h>
#include <stdlib.h> 
#include <assert.h> 
#include<math.h>

typedef struct node
{
  int value;
  struct node* next;
} node;

/* terminal node at the end of the list */
node SENTINEL = {0, 0};

/* utility functions to create and free lists */
node * make_node(int v, node * q)
{
  node* p = (node*) malloc(sizeof(node));
  p->value = v;
  p->next = q;
  return p;
}

int sum_squares(node* list)
{
    if(list == 0)
        return 0;
    else
    {
        return(pow(&list, 2) + sum_squares(list));
    }
    
    
}
void free_node(node* p)
{
  if(p == &SENTINEL)
    return;
  else
  {
    free_node(p->next);
    free(p);
  }
}

int main(void)
{
    int sum;
    node* list =    
        make_node(1,
            make_node(2,
                make_node(3,
                    make_node(4,
                        make_node(5, &SENTINEL)
                    )
                )
            )
        );
    sum = sum_squares(list);

    printf("The sum of squares is: %d\n",sum);
  free_node(list);

  return 0;
} 

它应该等于 55 与当前数字

【问题讨论】:

    标签: c recursion linked-list


    【解决方案1】:

    您应该编辑一些内容!

    • 在您的sum_squares 函数中,您的基本案例检查当前节点list 是否等于0,但您应该检查它是否是哨兵节点。
    • 在递归情况下,您应该使用pow(&amp;list, 2)。但是,&amp;list 返回参数list 的地址。您正在寻找的是节点结构中保存的整数值,您可以使用-&gt; 运算符获得该值。 &amp;list 变为 list-&gt;value
    • 最后,当您递归调用下一个函数时,您会将相同的节点传递给它。这将导致它在同一个节点上无限地调用自己,并且永远不会真正遍历列表。不要只是再次传递list,你应该传递list-&gt;next

    更改应用如下:

    int sum_squares(node* list)
    {
        if (list == &SENTINEL)
            return 0;
    
        return (pow(list->value, 2) + sum_squares(list->next));
    }
    

    【讨论】:

    • pow(list-&gt;value, 2) 涉及浮点问题和简单的list-&gt;value * list-&gt;value 没有的问题。
    猜你喜欢
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 2016-06-11
    • 2014-03-29
    • 1970-01-01
    相关资源
    最近更新 更多