Informatică Programare

Cum implementez o stiva in Pascal?

O stivă în Pascal se implementează ca o structură de date LIFO (Last In, First Out) folosind un array și un indice pentru vârf. Elementele se adaugă și se elimină doar din partea superioară.

Declararea stivei

  • Tipul stivei const MAX = 100; type TStiva = record elem: array[1..MAX] of integer; vf: integer; end;
  • Inițializare procedure Init(var s: TStiva); begin s.vf := 0; end;
  • Verificare gol function EsteGoala(s: TStiva): boolean; begin EsteGoala := (s.vf = 0); end;

Operații principale

  1. 1
    Push (adaugare) procedure Push(var s: TStiva; x: integer); begin if s.vf < MAX then begin s.vf := s.vf + 1; s.elem[s.vf] := x; end else writeln('Stiva plina'); end;
  2. 2
    Pop (eliminare) function Pop(var s: TStiva): integer; begin if not EsteGoala(s) then begin Pop := s.elem[s.vf]; s.vf := s.vf - 1; end else writeln('Stiva goala'); end;
  3. 3
    Exemplu de utilizare var s: TStiva; begin Init(s); Push(s, 10); Push(s, 20); writeln(Pop(s)); // Afișează 20 end.

Testează întotdeauna stiva pentru gol/plin înainte de operații.

Mai multe din Programare