DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simple Stack //Pascal Class

06.15.2006
| 11869 views |
  • submit to reddit
        A simple pointer stack...

unit Stack;

interface

uses
  SysUtils, Classes;

type
  TStack = class
  private
    FList: PPointerList;
    FCapacity, FCount: Cardinal;
    procedure Grow;
  public
    destructor Destroy; override;
    procedure Push( const Data: Pointer );
    function Pop: Pointer;
  end;

implementation

{ TStack }

destructor TStack.Destroy;
begin
  FreeMem( FList );
  inherited;
end;

procedure TStack.Grow;
begin
  if FCapacity > 64 then
    Inc( FCapacity, FCapacity div 4 )
  else
    if FCapacity > 8 then
      Inc( FCapacity, 16 )
    else
      Inc( FCapacity, 4 );
  ReallocMem( FList, FCapacity * SizeOf( Pointer ) );
end;

function TStack.Pop: Pointer;
begin
  if FCount > 0 then
  begin
    Dec( FCount );
    Result := FList^[FCount];
  end
  else
    Result := nil;
end;

procedure TStack.Push(const Data: Pointer);
begin
  if FCapacity = FCount then
    Grow;
  FList^[FCount] := Data;
  Inc( FCount );
end;

end.