Implementation of a Stack Using Pointers

The program described here implements a stack as a series of linked nodes within an object-oriented framework. First we need to define some basic types and a class for the stack:

type
 datatype=string[10];
 TStackListPointer=^TStackListNode;
 TStackListNode=record
   name:datatype;
   next:TStackListPointer;
 end;
 TStack=class (TObject)
 private
  f_pointer:TStackListPointer;
 public
  procedure push;
  procedure pop;
  procedure display;
end;

A stack object is created when the form is opened and its first_pointer set to nil:

procedure TForm1.FormCreate(Sender: TObject);
begin
MyStack:=TStack.Create;
MyStack.f_pointer:=nil;
end;

When the program closes the stack object is removed from memory:

procedure TForm1.FormDestroy(Sender: TObject);
begin
MyStack.Free;
end;

A button click is used to push an item on to the stack and to display its contents:

procedure TForm1.Button1Click(Sender: TObject);
begin
 MyStack.Push;
 MyStack.Display;
end;

The details of the push operation are:

procedure TStack.push;
var newnamenode:TStackListPointer;
begin
 new(newnamenode);
 newnamenode^.name:=form1.edit1.text;
 if f_pointer=nil then
 begin       
//first node item added
  f_pointer:=newnamenode;
  f_pointer^.next:=nil;
 end
 else
 begin      
//stack already has nodes
  newnamenode^.next:=f_pointer;
  f_pointer:=newnamenode;
//new node in front of previous one
 end;
 display;
end;

The code for the pop operation is as follows:

procedure TStack.pop;
var c_pointer:TStackListPointer;
begin
 if (f_pointer=nil) then
 showmessage('Stack empty')
//cannot pop empty stack
 else
 if (f_pointer^.next=nil) then
//one item in stack
 f_pointer:=nil                    
//popping item so no need to point to it
 else
 begin                               
//more than one item in stack
  c_pointer:=f_pointer;
  f_pointer:=c_pointer^.next;
//move front pointer to next stack item
  dispose(c_pointer);           
//don't dispose f_pointer!!
  display;                          
//stack not empty so display it
 end;
end;

The display code is as follows:

procedure TStack.display;
var c_pointer:TStackListPointer;
begin
 form1.listbox1.clear;
 c_pointer:=f_pointer;
 if c_pointer=nil then
 showmessage('stack empty')
 else
 while not (c_pointer^.next=nil) do
 begin
  form1.listbox1.Items.add(c_pointer^.name);
  c_pointer:=c_pointer^.next;
 end;
end;

A known problem with this code is that the button has to be clicked twice to get the first item onto the stack and displayed.

Back