home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
ftp.disi.unige.it
/
2015-02-11.ftp.disi.unige.it.tar
/
ftp.disi.unige.it
/
pub
/
.person
/
CataniaB
/
teach-act
/
testi-esami
/
labo-6.99
/
turno1
/
parte3.c
< prev
next >
Wrap
C/C++ Source or Header
|
1999-06-16
|
2KB
|
150 lines
/* Una possibile soluzione Esame di Laboratorio di Algoritmi 15 giugno 1999
* Turno 1 */
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
/* definizione dei tipi */
typedef struct stackel * stack; /* uno stack e' un puntatore */
typedef struct stackel{ int el; stack next; } stck;
/* operazioni sullo stack */
stack empty(void); /* restituisce uno stack vuoto, cioe' restituisce NULL */
stack push(int,stack); /* aggiunge in testa */
void print(stack); /* stampa lo stack */
stack makestackel(void); /* alloca una nuova cella */
stack pop(stack); /* toglie elemento in testa */
int top(stack); /* restituisce elemento in testa */
/* main */
main()
{
FILE * fp;
char nome[MAX];
int n;
stack s;
/* creo stack vuoto */
s = empty();
/* leggo il nome del file */
printf("Fornisci il nome del file: ");
scanf("%s", nome);
/* apro il file in lettura */
fp = fopen(nome,"r");
/* carico lo stack con i dati letti da file
* (assumendo il file del formato corretto */
while (fscanf(fp,"%d",&n) && n != -1)
s = push(n,s);
/* stampo lo stack */
print(s);
/* determino l'elemento in testa */
n = top(s);
/* stampo l'elemento in testa, se lo stack non e' vuoto */
if (n != -1)
printf("\nL'elemento in testa allo stack e' %d\n",n);
else
printf("\nLo stack non contiene elementi\n");
/* cancello i primi due elementi dello stack */
s = pop(pop(s));
printf("\nHo cancellato i primi due elementi\n");
/* determino l'elemento in testa */
n = top(s);
/* stampo l'elemento in testa, se lo stack non e' vuoto */
if (n != -1)
printf("\nL'elemento in testa allo stack e' %d\n",n);
else
printf("\nLo stack non contiene elementi\n");
}
/* funzioni */
stack empty()
{
return NULL;
}
stack push(int el, stack s)
{
stack t;
t=makestackel();
t->el=el;
t->next=s;
return t;
}
stack pop(stack s)
{
stack t;
if (s == NULL) return NULL;
else
{
t=s;
s=s->next;
free(t);
return s;
}
}
int top(stack s)
{
if (s == NULL) return -1;
else return s->el;
}
stack makestackel(){ return (stack)malloc(sizeof(stck)); }
void print(stack s)
{
printf("\nLo stack ha il seguente contenuto: ");
for(; s !=NULL ; s = s -> next)
printf(" %d",s->el);
printf("\n\n");
}