Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- main.c
- #include "funz.h"
- int main(){
- char str[N] = "";
- Lista *testa;
- testa = NULL;
- printf("\nInserire stringa(non più di 50 caratteri): ");
- fgets(str, N, stdin);
- testa = funzione(testa, str);
- stampa(testa);
- return 0;
- }
- funz.h
- #include <stdlib.h>
- #include <stdio.h>
- #include <malloc.h>
- #include <string.h>
- #include <ctype.h>
- #define N 51
- typedef struct elemento{
- char parola[N];
- struct elemento *next;
- } Lista;
- Lista *funzione(Lista *, char []);
- Lista *inserimento(Lista *, char []);
- void stampa(Lista *);
- funz.c
- #include "funz.h"
- Lista *funzione(Lista *h, char stringa[]){ //h è il puntatore alla testa della lista
- int l, j = 0;
- char strapp[N] = " "; //stringa di appoggio dove inserisco la parola
- l = strlen(stringa);
- for(int i = 0; i<(l+1); i++){
- if(stringa[i] != ' ' && stringa[i]!= '\n'){ //seconda condizione necessaria perchè utilizzo fgets
- strapp[j] = stringa[i];
- j++;
- }
- if(stringa[i] == ' ' || stringa[i] == '\0'){
- strapp[j] = '\0'; //inserisco carattere di terminazione stringa
- h = inserimento(h, strapp); //inserisco la parola nella lista
- strapp[0] = '\0'; //"reinzializzo la stringa che contiene la parola"
- j = 0;
- }
- }
- return h;
- }
- Lista *inserimento(Lista *h, char string[N]){
- Lista *app, *p;
- p = h;
- if(h == NULL){ // se la lista è vuota inserisco la testa
- h = (Lista *)malloc(sizeof(Lista));
- if(h != NULL){
- strcpy(h->parola, string); //copio string(parola ricevuta in input) nel campo parola della lista
- h->next = NULL;
- } else printf("\nAlocazione non riuscita, valore non inserito in lista!");
- }
- else{ //se la lista non è vuota aggiungo in coda
- app = (Lista *)malloc(sizeof(Lista));
- if(app != NULL){
- strcpy(app->parola, string);
- app->next = NULL;
- while(p->next != NULL) p = p->next;
- p->next = app;
- } else printf("\nAlocazione non riuscita, valore non inserito in lista!");
- }
- return h;
- }
- void stampa(Lista *h){
- Lista *p;
- p = h;
- printf("\n");
- while(p != NULL){
- printf("<%s>, ", p->parola);
- p = p->next;
- }
- printf("\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement