this is what i put together but I did something wrong, received some errors and dont know where to begin to fix them.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct listNode {
struct listNode *nextPtr;
int nums;
};
typedef struct listNode ListNode;
typedef ListNode *ListNodePtr;
void printList( ListNodePtr currentPtr );
int generateList( ListNodePtr *startPtr );
int main()
{
int total;
ListNodePtr startPtr = NULL;
generateList( &startPtr );
total = get_total(startPtr);
printList( startPtr );
printf( "\n\n\nTotal: %d", total );
printf( "\nAverage: %.2f\n\n", (float)total / 25 );
getchar();
return 0;
}
int generateList( ListNodePtr *startPtr )
{
int randNum, total = 0, i = 0;
ListNodePtr newPtr, currentPtr;
srand( time( NULL ) );
for (i =0; i < 25; i++ ) {
randNum = rand() % 100;
newPtr = malloc( sizeof( ListNode ) );
newPtr->nums = randNum;
newPtr->nextPtr = NULL;
if(*startPtr == NULL) {
*startPtr = newPtr;
currentPtr=newPtr;
continue;
}
currentPtr->nextPtr=newPtr;
currentPtr=currentPtr->nextPtr;
}
insertion_sort_list(&startPtr);
return 0;
}
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->nums );
currentPtr = currentPtr->nextPtr;
}
}
}
int get_total(ListNodePtr currentPtr)
{
if(currentPtr==NULL) return 0;
return currentPtr->nums + get_total(currentPtr->nextPtr);
}
int insertion_sort_list(ListNodePtr *startPtr)
{
struct node *newStart = NULL;
struct node *newPtr;
struct node *newPtrNext;
struct node *nextPtr;
struct node *nextPtrPrev;
for ( newPtr = startPtr; newPtr; newPtr = newPtrNext) {
newPtrNext = newPtr->next;
// Simplest case - new list is empty, insert current element first.
if (newStart == NULL) {
newStart = newPtr;
newPtr->next = NULL;
} else {
nextPtrPrev = NULL;
for(nextPtr = newStart; nextPtr->data < newPtr->data; nextPtrPrev = nextPtr, nextPtr = nextPtr->next);
// Is the current value smaller than first item in the list?
// If so, make this a new head.
if (nextPtrPrev == NULL) {
newPtr->next = newStart;
newStart = newPtr;
} else {
nextPtrPrev->next = newPtr;
newPtr->next = nextPtr;
}
}
}
return newStart;
}