Esempio di dichiarazione di nodo di lista singola con campo informativo di tipo intero struct nodo_s { int info; struct nodo_s * next; }; Esempio di dichiarazione di puntatore alla testa della lista struct nodo_s * head; Per inserire un nodo in una lista le operazioni essenziali sono: 1) capire in quale posizione inserire 2) eseguire l'inserimento: 2a) creare un nuovo nodo 2b) caricarlo con i valori desiderati 2c) inserire il nodo alla sua posizione corretta (aggiustando i puntatori come necessario) =============================================== CREARE E INSERIRE NUOVO NODO IN SECONDA POSIZIONE IN LISTA SINGOLA Con utilizzo di variabile temporanea struct nodo_s * nuovonodo; struct nodo_s * temporaneo; temporaneo = head->next; nuovonodo = (struct nodo_s *)malloc(sizeof(struct nodo_s)); nuovonodo->info = 7; head->next=nuovonodo; nuovonodo->next=temporaneo; =============================================== INSERIRE NUOVO NODO IN SECONDA POSIZIONE IN LISTA SINGOLA Senza utilizzo di variabile temporanea struct nodo_s * nuovonodo; nuovonodo = (struct nodo_s *)malloc(sizeof(struct nodo_s)); nuovonodo->info = 7; nuovonodo->next=head->next; head->next=nuovonodo; =============================================== RIMUOVERE SECONDO NODO DA LISTA SINGOLA 1. "scavalcare" il secondo nodo 2. rilasciare mem. è necessario procurarsi un puntatore temporaneo al nodo da rimuovere: struct nodo_s * temporaneo; temporaneo = head->next; head->next=head->next->next; free(temporaneo); NON COSI': (una volta rilasciato, un nodo non può più essere acceduto!) free(head->next); head->next=head->next->next; ==================================================== INSERIRE NUOVO NODO IN SECONDA POSIZIONE IN LISTA DOPPIA struct nodo_s * nuovonodo; nuovonodo->next = head->next; head->next = nuovonodo; nuovonodo->prev = head; nuovonodo->next->prev = nuovonodo; ================================ RIMUOVERE SECONDO NODO DA LISTA DOPPIA head->next = head->next->next; free(head->next->prev); head->next->prev=head; ========================= ACCEDERE AL CAMPO INFORMATIVO DEL TERZO NODO DELLA LISTA int x = head->next->next->info; oppure (solo se la lista ha tre nodi!) int x = tail->info; =========================== LEGGERE CAMPO INFORMATIVO DI TIPO INTERO ('info') DEL SECONDO NODO DI UNA LISTA DOPPIA DI TRE ELEMENTI si può arrivare anche dalla coda, così: scanf("%d", & (tail->prev->info)); LEGGERE CAMPO INFORMATIVO DI TIPO STRINGA ('cognome') DEL PRIMO NODO DI UNA LISTA SINGOLA scanf("%s", head->cognome) ==========================================