How to implement a stack in Pascal

1 Answer

0 votes
program StackExample;

{$mode objfpc}  { enables modern Free Pascal features }

type
  TStack = record
    Data: array of Integer;
    Top: Integer;
  end;

{ Initialize stack with a given capacity }
procedure InitStack(var S: TStack; Capacity: Integer);
begin
  SetLength(S.Data, Capacity);
  S.Top := -1;
end;

function IsEmpty(const S: TStack): Boolean;
begin
  Result := S.Top = -1;
end;

function IsFull(const S: TStack): Boolean;
begin
  Result := S.Top = High(S.Data);
end;

procedure Push(var S: TStack; Value: Integer);
begin
  if IsFull(S) then
    Writeln('Stack overflow')
  else
  begin
    Inc(S.Top);
    S.Data[S.Top] := Value;
  end;
end;

function Pop(var S: TStack): Integer;
begin
  if IsEmpty(S) then
  begin
    Writeln('Stack underflow');
    Result := 0;
  end
  else
  begin
    Result := S.Data[S.Top];
    Dec(S.Top);
  end;
end;

function Top(const S: TStack): Integer;
begin
  if IsEmpty(S) then
  begin
    Writeln('Stack is empty');
    Result := 0;
  end
  else
    Result := S.Data[S.Top];
end;

procedure PrintStack(const S: TStack);
var
  I: Integer;
begin
  Write('Stack (top → bottom): ');
  for I := S.Top downto 0 do
    Write(S.Data[I], ' ');
  Writeln;
end;

{ ---------------- MAIN PROGRAM ---------------- }

var
  S: TStack;
  X: Integer;

begin
  InitStack(S, 10);

  Push(S, 10);
  Push(S, 20);
  Push(S, 30);
  Push(S, 40);
  Push(S, 50);

  PrintStack(S);

  X := Pop(S);
  Writeln('Popped: ', X);

  PrintStack(S);
end.




(*
run:

Stack (top → bottom): 50 40 30 20 10 
Popped: 50
Stack (top → bottom): 40 30 20 10 

*)

 



answered 3 hours ago by avibootz
...