const max = 5; (* massima dimensione *) empty_el = 9999; type (* dichiarazione della struttura STACK o PILA *) stack = RECORD elements: array[1..max] of integer; top: 1..max; (* indica il top dello stack *) END (* end record *) (* Funzioni/Procedure di base: create(stack); full(stack) --> boolean; empty(stack) --> boolean; push(stack, integer); pop(stack) --> integer; *) (* CREA STACK *****************************************) (* procedura di inizializzazione *) procedure create(S: stack); begin S.top := 0; (* stato di stack vuoto *) end; (* STACK PIENO *****************************************) function full(S: stack): boolean; begin full := (S.top=max); end; (* STACK VUOTO *****************************************) function empty(S: stack): boolean; begin empty := (S.top=0); end; (* INSERIMENTO NELLO STACK *****************************) (* restituisce TRUE se l'elemento è stato inserito *) function push(var S: stack; x: integer): boolean; begin if(not full(S)) then begin S.top := S.top+1; (* il top si sposta su *) S.elements[S.top] := x; push := true; end else push := false; end; (* ESTRAZIONE DALLO STACK ******************************) function pop(var S: stack): integer; begin if(not empty(S)) then begin pop := S.elements[S.top]; S.top := S.top-1; (* il top si sposta giù *) end else pop := empty_el; end; (* PROCEDURA: somma degli elementi dello stack; lo stack è passato per valore: non verrà dunque modificato. *) function sum(S: stack): integer; var tot: integer; begin tot := 0; while(not empty(S)) tot := tot + pop(S); sum := tot; end;