putting linked list in order
hi people, i made a program that puts 25 random integers into a linked list, and then finds the sum and average. everything works fine, one thing im wondering is if i wanted to put these numbers in order from lowest to highest how can i walk through the list to do that? I know the for loop needs to be there walking through num 1-25 but im not sure how to compare them with pointers in a linked list. thanks for the help.
Code:
#include <stdio.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;
generateList( &startPtr );
total = get_total(startPtr);
printList( startPtr );
printf( "\nTotal of all 25 elements is %d", total );
printf( "\nAverage of all 25 elements is %.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->data = randNum;
newPtr->nextPtr = NULL;
if(*startPtr == NULL) {
*startPtr = newPtr;
currentPtr=newPtr;
continue;
}
currentPtr->nextPtr=newPtr;
currentPtr=currentPtr->nextPtr;
}
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->data );
currentPtr = currentPtr->nextPtr;
}
printf( "NULL\n\n" );
}
}
int get_total(ListNodePtr currentPtr)
{
if(currentPtr==NULL) return 0;
return currentPtr->data + get_total(currentPtr->nextPtr);
}