fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <stdbool.h>
  5.  
  6. struct node {
  7. char key;
  8. int data;
  9. struct node *next;
  10. };
  11. struct node *head = NULL;
  12. struct node *current = NULL;
  13.  
  14. //insert link at the first location
  15. void insertFirst(int key, int data) {
  16. //create a link
  17. struct node *link = (struct node*) malloc(sizeof(struct node));
  18.  
  19. link->key = key;
  20. link->data = data;
  21.  
  22. //point it to old first node
  23. link->next = head;
  24.  
  25. //point first to new first node
  26. head = link;
  27. }
  28.  
  29. //display the list
  30. void printList() {
  31. struct node *ptr = head;
  32. printf("\n[ ");
  33.  
  34. //start from the beginning
  35. while(ptr != NULL) {
  36. printf("(%c,%d) ",ptr->key,ptr->data);
  37. ptr = ptr->next;
  38. }
  39.  
  40. printf(" ]");
  41. }
  42.  
  43. int main() {
  44. insertFirst('A',300);
  45. insertFirst('B',0);
  46. insertFirst('C',100);
  47. insertFirst('D',200);
  48.  
  49. struct node *tmp = head;
  50. int avg=0;
  51. while(tmp != NULL) {
  52. avg=avg+tmp->data;
  53. tmp = tmp->next;
  54. }
  55. avg=avg/4;
  56. printf("avg=%d\n",avg);
  57. printf("Original List: ");
  58. //print list
  59. printList();
  60.  
  61.  
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
avg=150
Original List: 
[ (D,200) (C,100) (B,0) (A,300)  ]