ExplicationToute les fonctions pour l'implémentation de la liste se trouvent dans le fichier liste_funct.c. | |||||||||||||||||||||||||||||||||||||||||||||||||
| $ ./lmoyenneelements Nom fichier ? fic.txt 1 1 2 3 1 1 1 4 5 2 La moyenne des éléments est : 2.10 |
#ifndef __LISTE__ #define __LISTE__ typedef struct Element{ int donnee; struct Element *suivant; }Liste; Liste *InitialiserListe(); Liste *InsertionDebutListe(Liste *L,int donnee); Liste *InsertionFinListe(Liste *L,int donnee); Liste *CreerListeDansOrdre(); Liste *CreerListeInverse(); void ViderListe(Liste **L); void AfficheListe(Liste *L); Liste *alloc(); Liste *CreerListeDepuisFichier(char *nomfichier); #endif |
#include "liste.h" #include<stdio.h> #include<stdlib.h> #include<string.h> Liste *InitialiserListe(){ return NULL; } Liste *alloc(){ return (Liste *)malloc(sizeof(Liste)); } Liste *InsertionDebutListe(Liste *L,int donnee){ Liste *nouveau; nouveau = alloc(); nouveau->donnee = donnee; nouveau->suivant = NULL; nouveau->suivant=L; return nouveau; } Liste *CreerListeInverse(){ Liste *L; char c = 'o'; int N; L=InitialiserListe(L); while(c=='o'){ printf("Entrez numéro : "); scanf("%d",&N); getchar(); L = InsertionDebutListe(L,N); printf("Continuer ? o/n : "); c=getchar(); } return L; } Liste *InsertionFinListe(Liste *L,int donnee){ Liste *nouveau,*pL; nouveau = alloc(); nouveau->donnee = donnee; nouveau->suivant = NULL; if(L==NULL) L=nouveau; else{ for(pL=L;pL->suivant!=NULL;pL=pL->suivant) ; pL->suivant=nouveau; } return L; } Liste *CreerListeDansOrdre(){ Liste *L; char c = 'o'; int N; L=InitialiserListe(L); while(c=='o'){ printf("Entrez numéro : "); scanf("%d",&N); getchar(); L = InsertionFinListe(L,N); printf("Continuer ? o/n : "); c=getchar(); } return L; } void AfficheListe(Liste *L){ Liste *pL; for(pL=L;pL!=NULL;pL=pL->suivant) printf("%d ",pL->donnee); printf("\n"); } void ViderListe(Liste **L){ Liste *courant; while(*L!=NULL){ courant=*L; *L=(*L)->suivant; free(courant); } *L=NULL; } Liste *CreerListeDepuisFichier(char *nomfichier){ FILE *F; Liste *L; int n; L=InitialiserListe(); F=fopen(nomfichier,"r"); while((n=fgetc(F))!=EOF) if(n!='\n') L=InsertionFinListe(L,n-'0'); return L; } |
| $ cat fic.txt 1 1 2 3 1 1 1 4 5 2 |