1
0
Files
Laboratori-ASD/Laboratorio 7/Esercizio 1/pgList.c
2024-03-22 17:37:24 +01:00

132 lines
2.6 KiB
C

// Laboratorio 7 - Esercizio 1 - pgList.c
// Matteo Schiff - s295565
#ifndef PGLIST_C_DEFINED
#define PGLIST_C_DEFINED
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "pgList.h"
typedef struct node_s *link;
typedef struct node_s {
pg_t val;
link next;
} node;
/* ADT di prima classe collezione di personaggi */
typedef struct pgList_s {
link head;
link tail;
int nPg;
} *pgList_t;
link new_node(pg_t val, link next) {
link t = malloc(sizeof(node));
if (t == NULL) {
printf("ERROR: out of memory");
exit(2);
}
t->val = val;
t->next = next;
return t;
}
void free_node(link p) {
pg_clean(&p->val);
free(p);
}
/* creatore e distruttore */
pgList_t pgList_init() {
pgList_t new = malloc(sizeof(struct pgList_s));
new->head = NULL;
new->tail = NULL;
new->nPg = 0;
return new;
}
void pgList_free(pgList_t pgList) {
link p, x;
for (p = pgList->head, x = pgList->head->next; x != NULL; p = x, x = x->next){
free_node(p);
}
free(pgList);
}
/* lettura e scrittura su file */
void pgList_read(FILE *fp, pgList_t pgList) {
while (!feof(fp))
{
pg_t pgp;
if (pg_read(fp, &pgp) != 0) {
pgList_insert(pgList, pgp);
}
}
}
void pgList_print(FILE *fp, pgList_t pgList, invArray_t invArray) {
link p;
for (p = pgList->head; p != NULL; p = p->next) {
pg_print(fp, &(p->val), invArray);
}
}
/* inserimento di un nuovo personaggio */
void pgList_insert(pgList_t pgList, pg_t pg) {
link new = new_node(pg, NULL);
if (pgList->head == NULL) {
pgList->head = new;
} else {
pgList->tail->next = new;
}
pgList->tail = new;
}
/* cancellazione con rimozione */
void pgList_remove(pgList_t pgList, char* cod) {
link p, x;
if (pgList->head == NULL)
return;
for (x = pgList->head, p = NULL; x != NULL; p = x, x = x->next) {
if (!strcmp(x->val.cod, cod)) {
if (p == NULL) {
pgList->head = x->next;
} else {
p->next = x->next;
// se tolgo l'ultimo elemento devo aggiornare `tail`
if (x->next == NULL)
pgList->tail = p;
}
free_node(x);
break;
}
}
}
/* ricerca per codice, ritornando il puntatore */
pg_t *pgList_searchByCode(pgList_t pgList, char* cod) {
link p;
for (p = pgList->head; p != NULL; p = p->next) {
if (!strcmp(p->val.cod, cod)) {
return &(p->val);
}
}
return NULL;
}
/* Si possono aggiungere altre funzioni se ritenute necessarie */
#endif