informaticage

Linked List - Aoclel

Jul 31st, 2021
690
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct _mark {
  5.   unsigned int mark;
  6.   struct _mark* next;
  7. } Mark;
  8.  
  9. Mark* append(Mark* head, unsigned int mark);
  10. void print_list(Mark* head);
  11. void free_list(Mark* head);
  12.  
  13. int main() {
  14.   printf("Linked List\n");
  15.  
  16.   // Inizializziamo una lista vuota
  17.   // struct _mark *marks_list = NULL;
  18.   Mark* marks_list = NULL;
  19.  
  20.   marks_list = append(marks_list, 11);
  21.   marks_list = append(marks_list, 12);
  22.   marks_list = append(marks_list, 32);
  23.   marks_list = append(marks_list, 2);
  24.   marks_list = append(marks_list, 1);
  25.   marks_list = append(marks_list, 24);
  26.   marks_list = append(marks_list, 21);
  27.   marks_list = append(marks_list, 31);
  28.  
  29.   print_list(marks_list);
  30.  
  31.   free_list(marks_list);
  32.   return 0;
  33. }
  34.  
  35. void print_list(Mark* head) {
  36.   // Dalla testa alla coda, stampo tutti i mark e ogni volta passo al next
  37.   // finchè non diventa NULL
  38.   for (Mark* _iterator = head; _iterator != NULL; _iterator = _iterator->next) {
  39.     printf("%u -> ", _iterator->mark);
  40.   }
  41.  
  42.   printf("NULL\n");
  43. }
  44.  
  45. void free_list(Mark* head) {
  46.   if (head == NULL) return;
  47.  
  48.   printf("HEAD: %d\n", head->mark);
  49.  
  50.   if (head->next == NULL) {
  51.     printf("Killing: %d\n", head->mark);
  52.     free(head);
  53.     return;
  54.   }
  55.  
  56.   free_list(head->next);
  57.   printf("Killing: %d\n", head->mark);
  58.   free(head);
  59. }
  60.  
  61. Mark* append(Mark* head, unsigned int mark) {
  62.   // Se la lista è inizialmente vuota
  63.   if (head == NULL) {
  64.     Mark* new_head = (Mark*)malloc(sizeof(Mark));
  65.     new_head->mark = mark;
  66.     new_head->next = NULL;
  67.  
  68.     return new_head;
  69.   }
  70.  
  71.   // Scorre finchè c'è un next
  72.   Mark* _iterator;
  73.   for (_iterator = head; _iterator->next != NULL;) {
  74.     _iterator = _iterator->next;
  75.   }
  76.  
  77.   // Quando il next è NULL lo alloco
  78.   _iterator->next = (Mark*)malloc(sizeof(Mark));
  79.   _iterator->next->mark = mark;
  80.   _iterator->next->next = NULL;
  81.  
  82.   return head;
  83. }
  84.  
  85. // *a = 0x134;
  86. // *a = fun() = 0x134
  87.  
  88. // MEMORIA[0x134]  = { mark: 29, next: 0x700 };
  89. // MEMORIA[0x700]  = { mark: 22, next: 0x800 };
  90. // MEMORIA[0x800] = { mark: 11, next null };
  91.  
  92. // fun(a, b, c) {
  93. //   *it = a;
  94. //   finche( NULL != null) {
  95. //     it = it -> NULL;
  96. //   }
  97. //   it -> next = { mark: 11, next null;}
  98. //   return 0x134;
  99. // }
  100.  
RAW Paste Data