首页 > 解决方案 > 链表中的 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 与当前数字

标签: crecursionlinked-list

解决方案


您应该编辑一些内容!

  • 在您的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));
}

推荐阅读