fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct node {
  5. int value;
  6. struct node* next;
  7. };
  8. typedef struct node node_t;
  9.  
  10. node_t* create_linked_list(unsigned int number_of_nodes) {
  11. node_t* head = NULL;
  12.  
  13. for (unsigned int i = 1; i < number_of_nodes + 1; ++i) {
  14. /*
  15. * malloc might be necessary so that the node doesn't
  16. * get wiped from memory once the for loop is over?
  17. * TODO: Find out if that is why it's necessary.
  18. */
  19. node_t* node = malloc(sizeof(node_t));
  20. node->value = i;
  21. node->next = head;
  22. head = node;
  23. }
  24.  
  25. return head;
  26. }
  27.  
  28. void print_list(node_t* head) {
  29. node_t* temp = head;
  30.  
  31. while (temp != NULL) {
  32. printf("%d - ", temp->value);
  33. temp = temp->next;
  34. }
  35.  
  36. printf("\n");
  37. }
  38.  
  39. void clean_list(node_t* head) {
  40. node_t* current = head;
  41.  
  42. while (current != NULL) {
  43. node_t* temp = current;
  44. current = current->next;
  45. free(temp);
  46. }
  47.  
  48. printf("\nclean_list complete \n");
  49. }
  50.  
  51. int main(void) {
  52. node_t* head = create_linked_list(15);
  53.  
  54. printf("head address at beginning = %p\n", head);
  55. printf("head value at the beginning = %d\n\n", (*head).value);
  56.  
  57. print_list(head);
  58.  
  59. clean_list(head);
  60.  
  61. printf("\nhead address at the end = %p", head);
  62. printf("\nhead value at the end = %d", (*head).value);
  63.  
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0s 4776KB
stdin
Standard input is empty
stdout
head address at beginning = 0x55a30f0fe420
head value at the beginning = 15

15 - 14 - 13 - 12 - 11 - 10 - 9 - 8 - 7 - 6 - 5 - 4 - 3 - 2 - 1 - 

clean_list complete 

head address at the end = 0x55a30f0fe420
head value at the end = 0