c - C 中的用户定义函数和链接列表

标签 c linked-list

我对如何创建一个可以打印输出的用户定义函数有点困惑。我还必须创建一个用户定义的函数,将每个节点中的数据相加并打印出总数,但它的相加不正确,而且格式也有点不对劲。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char printout();
int sum();
typedef struct node
{
    int number;
    struct node*next;
} node;

char printout()
{

};
int sum()
{
    int s,sum_all=0, node_sum=0;
    for(s=0;s=100;s++)
    {
        sum_all=node_sum+s;
        return printf("The sum of all nodes is %d.\n",sum_all);
    };

};
int main()
{
    srand (time(NULL));
    int i, total=0;
    struct node*head=malloc(sizeof(struct node));
    head->number = rand()%100;
    printf("Node #%d contains %d.\n", 0, head->number);

    struct node*here=head;

    for (i=1; i<100; i++)
    {
        here->next=malloc(sizeof(struct node));
        here->number=rand()%100;
        printf("Node #%d contains %d.\n", i, here->number);
    };
    total=sum(here->number);
    printf("%2.2d", total);
    return 0;
}

最佳答案

这里有很多错误,但我们只关注最重要的内容:

您应该将列表的头部传递给函数 sum(),即

sum(head); // This is how you call most linked list functions.

您应该将标题更改为

int sum(struct node *head)
{ ... }

这不是一个数组。您应该正确遍历链表。

我无法向您展示所有代码,因为这是您的教授希望您学习的内容。

但是你应该使用这些

for( struct node*p = head; p!=NULL; p=p->next)

而不是这些

for( s=0; s<=100; s++)

您还忘记在 malloc-and-fill-with-rand 循环中向前迈进

这里=这里->下一步;//这在链表中的作用与 i++ 在数组中的作用相同

还有这个

sum_all += p->number; // p->number is analogous to array[i]

而不是

sum_all = node_sum +s; // what are s and node_sum anyway?

另外,如果你坚持要求总和返回一些东西, 它应该返回总和;

return sum_all;

并且不要在函数内打印它

printf("The sum of all nodes is %d.\n",sum_all); // please don't

因为您已经在外面打印它了。

total = sum(head);
printf("%2.2d", total);

请尝试先思考您的代码将要完成什么,而不是空白地放置代码。 这会对你有很大帮助。祝你好运!

关于c - C 中的用户定义函数和链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43564342/

相关文章:

c - 如何禁止可执行文件读取/修改给定目录以外的任何文件?

c - 如何链接正确的库以便 __aeabi_idiv 和 __aeabi_idivmod 工作?

c - 插入到链表中

跨多个 SQL 服务器的 SQL 查询

c - 我尝试打印列表时出现问题

c - XC8 寄存器声明冲突(例如 TRIS、SSP1CON1 等)

java - 添加新节点添加 LinkedList 的开头和末尾

C++:链表、字符串指针

c - 单链表插入函数

c - C 中奇怪的 malloc 行为