Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct _mark {
- unsigned int mark;
- struct _mark* next;
- } Mark;
- Mark* append(Mark* head, unsigned int mark);
- void print_list(Mark* head);
- void free_list(Mark* head);
- int main() {
- printf("Linked List\n");
- // Inizializziamo una lista vuota
- // struct _mark *marks_list = NULL;
- Mark* marks_list = NULL;
- marks_list = append(marks_list, 11);
- marks_list = append(marks_list, 12);
- marks_list = append(marks_list, 32);
- marks_list = append(marks_list, 2);
- marks_list = append(marks_list, 1);
- marks_list = append(marks_list, 24);
- marks_list = append(marks_list, 21);
- marks_list = append(marks_list, 31);
- print_list(marks_list);
- free_list(marks_list);
- return 0;
- }
- void print_list(Mark* head) {
- // Dalla testa alla coda, stampo tutti i mark e ogni volta passo al next
- // finchè non diventa NULL
- for (Mark* _iterator = head; _iterator != NULL; _iterator = _iterator->next) {
- printf("%u -> ", _iterator->mark);
- }
- printf("NULL\n");
- }
- void free_list(Mark* head) {
- if (head == NULL) return;
- printf("HEAD: %d\n", head->mark);
- if (head->next == NULL) {
- printf("Killing: %d\n", head->mark);
- free(head);
- return;
- }
- free_list(head->next);
- printf("Killing: %d\n", head->mark);
- free(head);
- }
- Mark* append(Mark* head, unsigned int mark) {
- // Se la lista è inizialmente vuota
- if (head == NULL) {
- Mark* new_head = (Mark*)malloc(sizeof(Mark));
- new_head->mark = mark;
- new_head->next = NULL;
- return new_head;
- }
- // Scorre finchè c'è un next
- Mark* _iterator;
- for (_iterator = head; _iterator->next != NULL;) {
- _iterator = _iterator->next;
- }
- // Quando il next è NULL lo alloco
- _iterator->next = (Mark*)malloc(sizeof(Mark));
- _iterator->next->mark = mark;
- _iterator->next->next = NULL;
- return head;
- }
- // *a = 0x134;
- // *a = fun() = 0x134
- // MEMORIA[0x134] = { mark: 29, next: 0x700 };
- // MEMORIA[0x700] = { mark: 22, next: 0x800 };
- // MEMORIA[0x800] = { mark: 11, next null };
- // fun(a, b, c) {
- // *it = a;
- // finche( NULL != null) {
- // it = it -> NULL;
- // }
- // it -> next = { mark: 11, next null;}
- // return 0x134;
- // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement