c - 链表中的 C 平方和
问题描述
您好,我正在尝试制作一个程序,该程序采用整数链表并对 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 与当前数字
解决方案
您应该编辑一些内容!
- 在您的
sum_squares
函数中,您的基本情况检查当前节点list
是否等于 0,但您应该检查它是否是哨兵节点。 - 在递归情况下,您应该使用
pow(&list, 2)
.&list
但是,返回参数的地址list
。您正在寻找的是节点结构中保存的整数值,您可以使用->
运算符获得。&list
变成list->value
. - 最后,当您递归调用下一个函数时,您将相同的节点传递给它。这将导致它在同一个节点上无限地调用自己,并且永远不会真正遍历列表。而不是
list
再次通过,你应该通过list->next
!
更改应用如下:
int sum_squares(node* list)
{
if (list == &SENTINEL)
return 0;
return (pow(list->value, 2) + sum_squares(list->next));
}
推荐阅读
- php - 如何从 LARAVEL 资源中的表中添加值
- git - 将 `git blame` 选项传递给 `git gui blame`
- javascript - ReactJS:类型数组的状态在重新渲染期间解构为元素
- ibm-watson - Watson ML CLI 授权失败
- c# - 在运行时,Winform 中出现意外和不需要的黑色边框
- angular - FormGroup.controls 在自定义验证器中未定义
- dialogflow-es - GCLOUD 中的权限问题
- r - 在 ggplot2 中使用堆积条形图排序数据
- r - 根据正则表达式拆分 data.table 列
- tensorflow - Tensorflow:每隔特定步骤保存指标