Linked list generates errors..
Hi,
Below is a program i wrote which generates 25 random numbers and store it in a linked list. Then the program should output the total of all elements ( which are integers ) in the list and also the floating-point average of the list. But when i run it, it generates errors. Pls give a hand and tell me what's wrong. It's my first program to use linked lists. Thnx in advance.
Code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
struct listNode {
struct listNode *nextPtr;
int data;
};
typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;
void printList( ListNodePtr currentPtr );
int generateList( ListNodePtr *startPtr );
int main()
{
int total;
ListNodePtr startPtr = NULL;
total = generateList( &startPtr );
printList( startPtr );
printf( "\nTotal of all 25 elements is %d", total );
printf( "\nAverage of all 25 elements is %.2f\n\n", total / 25 );
getch();
return 0;
}
/* Generate random list - returns sum of all elements */
int generateList( ListNodePtr *startPtr )
{
int randNum, total = 0, i = 0;
ListNodePtr newPtr, currentPtr, previousPtr;
srand( time( NULL ) );
previousPtr = NULL;
currentPtr = *startPtr;
for (; i < 25; i++ ) {
randNum = rand() % 100;
newPtr = malloc( sizeof( ListNode ) );
newPtr->data = randNum;
previousPtr->nextPtr = currentPtr;
currentPtr->nextPtr = newPtr;
total = total + randNum;
}
return total;
}
/* Print the list */
void printList( ListNodePtr currentPtr )
{
if ( currentPtr == NULL )
printf( "List is empty.\n\n" );
else {
printf( "The list is:\n" );
while ( currentPtr != NULL ) {
printf( "%d --> ", currentPtr->data );
currentPtr = currentPtr->nextPtr;
}
printf( "NULL\n\n" );
}
}