c-first-steps

a C playground
Index Commits Files Refs README
llist.c (1536B)
   1 #include <stdio.h>
   2 #include <stdlib.h>
   3 
   4 typedef struct node {
   5     char c;
   6     struct node *next;
   7 } node_t, *node_p;
   8 
   9 void insert(node_p *list, char c);
  10 void destroy(node_p *list);
  11 
  12 void print_list(node_p *first);
  13 
  14 int main (void)
  15 {
  16     node_p node = NULL; 
  17     /*    Now node points to NULL    */
  18     
  19     insert(&node, 'A');
  20     /*    Now node points to a struct containing the char 'A'    */
  21 
  22     insert(&node, 'B');
  23     print_list(&node);
  24 
  25     destroy(&node);
  26 
  27     return 0;
  28 }
  29 
  30 void insert(node_p *list, char c)
  31 {
  32     /*    Create new node    */
  33     node_p new_node;
  34     new_node = malloc(sizeof(node_t));
  35 
  36     /*    Storing the value on the new node    */
  37     new_node->c = c;
  38 
  39     /*    Storing the next node in a pointer on the new node    */
  40     new_node->next = *list;
  41 
  42     /*    Now node points to the new node    */
  43     *list = new_node;
  44 }
  45 
  46 void print_list(node_p *list)
  47 {
  48     if(*list == NULL)
  49         printf("List is empty.\n");
  50 
  51     /*    New node pointer to iterate over the list    */
  52     node_p current_node;
  53     current_node = *list;
  54 
  55     while(current_node != NULL) {
  56         printf("%c --> ", current_node->c);
  57         if(current_node->next == NULL)
  58             printf("NULL\n");
  59 
  60         current_node = current_node->next;
  61     }
  62 }
  63 
  64 void destroy(node_p *list)
  65 {
  66     /*    Frees memmory from first to last    */
  67     if(*list == NULL)
  68         return;
  69 
  70     /*    current it's a pointer to iterate over the list    */
  71     /*    tmp stores a copy of current to avoid losing the memory location    */
  72     node_p current, tmp;
  73     current = *list;
  74 
  75     while(current != NULL) {
  76         tmp = current;
  77 
  78         current = current->next;
  79 
  80         printf("freeing %c\n", tmp->c);
  81         free(tmp);
  82     }
  83     printf("All nodes were freed correctly.\n");
  84 }