unit Stack;
interface
uses
SysUtils;
type
PStackNode = ^TStackNode;
TStackNode = record
Data: Integer;
Next: PStackNode;
end;
TStack = class
private
FTop: PStackNode;
FCount: Integer;
public
constructor Create;
destructor Destroy
override;
procedure Clear;
procedure Push(Dat: Integer);
function Pop: Integer;
function IsEmpty: Boolean;
property Count: Integer read FCount;
end;
EStackEmpty = class(Exception);
implementation
constructor TStack.Create;
begin
FCount := 0;
FTop := nil;
end;
destructor TStack.Destroy;
begin
Clear;
end;
procedure TStack.Clear;
var
Ptr: PStackNode;
begin
Ptr := FTop;
while Assigned(FTop) do begin
FTop := FTop^.Next;
Dispose(Ptr);
Ptr := FTop;
end;
FCount := 0;
end;
procedure TStack.Push(Dat: Integer);
var
Ptr: PStackNode;
begin
New(Ptr);
with Ptr^ do begin
Data := Dat;
Next := FTop;
end;
FTop := Ptr;
Inc(FCount);
end;
function TStack.Pop: Integer;
var
Ptr: PStackNode;
begin
if FCount = 0 then
Raise EStackEmpty.Create('No elements in the stack!');
Ptr := FTop;
FTop := FTop^.Next;
Result := Ptr^.Data;
Dispose(Ptr);
Dec(FCount);
end;
function TStack.IsEmpty: Boolean;
begin
Result := FCount = 0;
end;
end.
////////////////////////////////
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes,
Graphics, Controls, Forms, Dialogs,
Stack, StdCtrls;
type
TForm1 = class(TForm)
btnPush: TButton;
btnPop: TButton;
btnCount: TButton;
btnEmpty: TButton;
btnClear: TButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject
var Action: TCloseAction);
procedure btnPushClick(Sender: TObject);
procedure btnPopClick(Sender: TObject);
procedure btnCountClick(Sender: TObject);
procedure btnEmptyClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
private
{ Private declarations }
Stack: TStack;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
Stack := TStack.Create;
end;
procedure TForm1.FormClose(Sender: TObject
var Action: TCloseAction);
begin
Stack.Free;
end;
procedure TForm1.btnPushClick(Sender: TObject);
var
Value: Integer;
begin
Value := Random(100);
Stack.Push(Value);
ShowMessage('You have push ' + IntToStr(Value) + ' into the stack!');
end;
procedure TForm1.btnPopClick(Sender: TObject);
begin
ShowMessage('You have pop ' + IntToStr(Stack.Pop) + ' out of the stack!');
end;
procedure TForm1.btnCountClick(Sender: TObject);
begin
ShowMessage('There are ' + IntToStr(Stack.Count) + ' number(s) in the stack!');
end;
procedure TForm1.btnEmptyClick(Sender: TObject);
begin
if Stack.IsEmpty then
ShowMessage('The stack is empty!')
else ShowMessage('The stack is not empty!');
end;
procedure TForm1.btnClearClick(Sender: TObject);
begin
Stack.Clear;
ShowMessage('You have just cleared the stack!');
end;
end.