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 / laboratorio / lab-19-4-99 / ese8a.c < prev    next >
C/C++ Source or Header  |  1999-05-10  |  1KB  |  80 lines

  1. /* tipo di dato stack di interi: 
  2. in questa prima versione, uno stack e' un array di interi,
  3. e viene sempre visto come variabile globale dalle 
  4. funzioni (come fatto a lezione).
  5. Ne vedremo altre versioni piu' eleganti */
  6.  
  7.  
  8.  
  9. #include <stdio.h>
  10. #define MAX 10
  11.  
  12. char stack[MAX];
  13. int sp = 0;         /* indice prima posizione libera */
  14.                 /* provare a rifare l'esercizio usando una struttura */
  15.  
  16. /* operazioni sullo stack */ 
  17.  
  18. int isempty(void); /* determina se lo stack e' vuoto */
  19. void push(int);   /* aggiunge in testa        */
  20. void pop(void);        /* toglie elemento in testa */
  21. int   top(void);        /* restituisce elemento in testa */
  22. void  print(void);
  23.  
  24. main()
  25. {
  26.     /* costruisco lo stack che contiene i seguenti elementi:
  27.     1 5 6 3 8 (questa e' la testa) */
  28.   push(1);
  29.   push(5);
  30.   push(6);
  31.   push(3);
  32.   push(8);
  33.     /* stampo lo stack */
  34.   print();
  35.     /*rimuovo la testa e stampo il nuovo stack*/
  36.   pop();
  37.   print();
  38.    /* rimuovo altri due elementi e stampo elemento in testa*/
  39.   pop();
  40.   pop();
  41.   printf("\nElemento in testa: %d",top());
  42.   return 0;
  43. }
  44.  
  45.  
  46. int isempty(void)
  47. {
  48.     return sp == 0 ;
  49. }    
  50.  
  51. void push(int el) 
  52.  { 
  53.     if (sp < MAX)
  54.         stack[sp++] = el;
  55.     else
  56.         printf("\n\nerrore:stack pieno \n\n");        
  57.  } 
  58.  
  59. void pop(void) 
  60.  { 
  61.     if (sp > 0)
  62.         --sp;
  63.  } 
  64.  
  65. int top(void) 
  66.  { 
  67.     return stack[sp-1];
  68.  } 
  69.  
  70.  
  71. void print(void) 
  72.  { 
  73.     int i;
  74.     printf("\nQuesto e' lo stack: ");
  75.     for(i = 0; i < sp ; i++)
  76.         printf("%d ",stack[i]);
  77.     printf("\n");
  78.  } 
  79.  
  80.