StackClassDemo

We suggest that a stack presents a good opportunity for you to try some object oriented programming. From the point of view of the programmer needing to use a stack, its method of implementation should be immaterial and the code can be "hidden" in its own unit. The methods are public and can be called from other units but the fields (variables) are private and so cannot be directly altered by code in other units.

Program StackClassDemo requires the program file and Stack.pas. To add Stack.pas to your program folder, create a new text file (File – New – Text), copy the code for unit Stack into it, then save it as Stack.pas.

program StackClassDemo;
  {$APPTYPE CONSOLE}
uses
  SysUtils, Stack in 'Stack.pas';
var
  Discards : TStack;
  Count : integer;
  strCards : array[1..4] of string = ('Q'#6, '5'#3,'A'#4, '3'#5);
  Card : string;
begin
  Discards := TStack.Create;
  for Count := 1 to 4 do
    Discards.Push(strCards[Count]);
  writeln(#13#10'Close to the end of a round of rummy',
          ' the discard pile is:');
  for Count := 4 downto 1 do
    writeln(strCards[Count]);
  writeln(#13#10'Player A removes the top discard (which is ',
          Discards.Pop,').');
  writeln('This must be popped from the stack.');
  writeln(#13#10'Player A then discards J'#4,'.');
  writeln('This must be pushed onto the stack.');
  Discards.Push('J'#4);
  writeln(#13#10'Player B picks up the top discard, which is ',
          Discards.Pop, '.');
  writeln('This must be popped from the stack.');
  writeln(#13#10'The result of popping the remaining stack four times is ...');
  for Count := 1 to 4 do
    begin
      Card := Discards.Pop;
      if Card = '' then
        writeln('Stack empty')
      else
        writeln(Card);
    end;
  readln;
end.

unit Stack;

interface

const
  MAX = 100;
type
  TStack = class(TObject)
  private
    StackTop : integer;
    StrStack: array[1 .. MAX] of string;
  public
    constructor Create;
    procedure Push(TopString: string);
    function Pop: string;
end;

implementation

constructor TStack.Create;
begin
  StackTop := 1;
end;

procedure TStack.Push(TopString: string);
begin
  if StackTop <= MAX then
    begin
      StrStack[StackTop] := TopString;
      inc(StackTop);
    end
  else
    begin
      writeln('Stack full so item could not be added.');
    end;
end;

function TStack.Pop: string;
begin
  if StackTop >= 2 then
    begin
      dec(StackTop);
      result := StrStack[StackTop];
    end
  else
    result := '';
end;

end.

Going Further

See also our Smart Pascal demonstration of searching a tree for the use of a stack to store indices of (a) nodes to be visited in a depth first search (DFS) and (b) preceding nodes from the target back to the starting node in order to retrieve the forward path to the target.

Programming - a skill for life!

Introduction to demonstrations of stacks