问题
I'm a bit stuck on how to make a user defined function that would printout the output. I also have to make a user defined function that will add up the data in each node and print out the total but it's not adding up correctly and the format is a little off as well.
#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;
}
回答1:
There is the litany of errors here, but let's just focus on the most important meat:
You should be pass the list's head to the function sum(), ie
sum(head); // This is how you call most linked list functions.
by which you should change the header to
int sum(struct node *head)
{ ... }
This is not an array. You should traverse the linked list correctly.
I can't show all the code for you, as this is what your professor wants you to learn.
But you should be using these
for( struct node*p = head; p!=NULL; p=p->next)
instead of these
for( s=0; s<=100; s++)
You also forgot to step forward in your malloc-and-fill-with-rand loop
here = here->next; // this does in linked lists what i++ does in arrays
and this
sum_all += p->number; // p->number is analogous to array[i]
instead of
sum_all = node_sum +s; // what are s and node_sum anyway?
Also, if you insist that sum return something, It should return, well, the sum;
return sum_all;
And don't print it inside the function
printf("The sum of all nodes is %d.\n",sum_all); // please don't
Because you're already printing it outside.
total = sum(head);
printf("%2.2d", total);
Please try to think first what your code is going to accomplish instead of putting code blankly. It will help you a lot. Good luck!
来源:https://stackoverflow.com/questions/43564342/user-defined-functions-and-linked-lists-in-c