listcalc.c (1469B)
1 /* Exercise 12.8 */ 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <time.h> 6 7 struct list { 8 int n; 9 struct list *next; 10 }; 11 12 typedef struct list List; 13 14 void insert(List **list, int value); 15 void showlist(List *list); 16 17 int main(void) 18 { 19 List *mylist = NULL; 20 int i, sum = 0; 21 double media = 0; 22 23 srand( time(NULL) ); 24 25 for(i = 0; i < 25; i++) 26 insert(&mylist, 1 + rand() % 100); 27 28 showlist(mylist); 29 30 /* calculate the sum */ 31 while( mylist != NULL ) { 32 sum += mylist->n; 33 ++media; 34 35 mylist = mylist->next; 36 } 37 38 media = sum / media; 39 40 printf("Sum: %d\nMedia: %.2f\n", sum, media); 41 42 return 0; 43 } /* E0F main */ 44 45 void showlist(List *list) 46 { 47 List *currentPtr = list; 48 49 while( currentPtr != NULL ) { 50 printf("%d --> ", currentPtr->n); 51 currentPtr = currentPtr->next; 52 } 53 54 printf("NULL\n"); 55 56 } /* eof showlist() */ 57 58 void insert(List **list, int value) 59 { 60 List *newPtr; 61 List *previousPtr = NULL, *currentPtr = *list;; 62 63 if( (newPtr = malloc( sizeof(List) )) == NULL) { 64 printf("Cannot allocate the memory\n"); 65 return; 66 } 67 newPtr->n = value; 68 newPtr->next = NULL; 69 70 while( currentPtr != NULL && value > currentPtr->n) { 71 previousPtr = currentPtr; 72 currentPtr = currentPtr->next; 73 } 74 75 if( previousPtr == NULL ) { 76 newPtr->next = *list; 77 *list = newPtr; 78 } 79 else { 80 previousPtr->next = newPtr; 81 newPtr->next = currentPtr; 82 } 83 84 } /* eof insert() */ 85