Stacks and queues in Pascal
last modified November 19, 2026 Free Pascal 3.2.2
A stack and a queue are sequences with restricted access. A stack is last in, first out: the most recently pushed element is the first one popped. A queue is first in, first out: elements leave in the order they arrived. This article starts with an array and a top index, then wraps the operations in procedures that report success with a Boolean, and only later uses a record, the generic containers, and a queue in a breadth-first search.
A stack is an array and a top index
The simplest stack needs no user-defined type and no procedures. An array
holds the elements, and an integer Top is the index of the last used slot.
Top = 0 means the stack is empty. Pushing increments
Top and stores a value; popping reads the value and decrements
Top.
program stack1;
{$mode objfpc}{$H+}
var
Items: array[1..5] of Integer;
Top: Integer;
begin
Top := 0;
Inc(Top);
Items[Top] := 10;
Inc(Top);
Items[Top] := 20;
Inc(Top);
Items[Top] := 30;
WriteLn('top: ', Items[Top]);
while Top > 0 do
begin
WriteLn(Items[Top]);
Dec(Top);
end;
end.
Three pushes store 10, 20, and 30, with 30 on top. The pop loop writes 30, 20,
and 10, the reverse of the insertion order. Nothing is erased: the values stay
in the array, but a later push overwrites the slot that Top points
to, so the old value is no longer part of the stack.
$ fpc -gl stack1.pas $ ./stack1 top: 30 30 20 10
Push and Pop as procedures
A record groups the array and the index, so a program can have more than one
stack. The procedures take the record as a var parameter, because
they modify it. Push and Pop return a Boolean instead
of raising an exception: the caller decides whether an overflow or an empty pop
is an error.
program stack2;
{$mode objfpc}{$H+}
const
MaxSize = 5;
type
TStack = record
Items: array[1..MaxSize] of Integer;
Top: Integer;
end;
procedure Init(var S: TStack);
begin
S.Top := 0;
end;
function Push(var S: TStack; Value: Integer): Boolean;
begin
Result := S.Top < MaxSize;
if Result then
begin
Inc(S.Top);
S.Items[S.Top] := Value;
end;
end;
function Pop(var S: TStack; out Value: Integer): Boolean;
begin
Result := S.Top > 0;
if Result then
begin
Value := S.Items[S.Top];
Dec(S.Top);
end;
end;
var
S: TStack;
Value: Integer;
begin
Init(S);
WriteLn('push 10: ', Push(S, 10));
WriteLn('push 20: ', Push(S, 20));
WriteLn('push 30: ', Push(S, 30));
while Pop(S, Value) do
WriteLn('pop: ', Value);
WriteLn('pop on empty: ', Pop(S, Value));
end.
Push returns False when the array is full and leaves
the stack unchanged. Pop returns False when the stack
is empty, and the out parameter is assigned only on success. The
last call asks for a value from an empty stack and receives
FALSE, which is a normal result rather than a crash. This style
suits a container that is used in a loop, where a failed operation is part of
the algorithm.
$ fpc -gl stack2.pas $ ./stack2 push 10: TRUE push 20: TRUE push 30: TRUE pop: 30 pop: 20 pop: 10 pop on empty: FALSE
Bracket matching with a stack
A stack is the natural tool for checking nested brackets. Every opening bracket is pushed, and every closing bracket must match the one on top, which is then popped. If a closing bracket arrives when the stack is empty, or if the types do not match, the text is unbalanced. At the end the stack must be empty.
program brackets;
{$mode objfpc}{$H+}
function IsBalanced(const S: string): Boolean;
var
Stack: array[1..256] of Char;
Top, I: Integer;
C: Char;
begin
Top := 0;
Result := False;
for I := 1 to Length(S) do
begin
C := S[I];
if (C = '(') or (C = '[') or (C = '{') then
begin
Inc(Top);
Stack[Top] := C;
end
else if (C = ')') or (C = ']') or (C = '}') then
begin
if Top = 0 then
Exit;
if ((C = ')') and (Stack[Top] <> '(')) or
((C = ']') and (Stack[Top] <> '[')) or
((C = '}') and (Stack[Top] <> '{')) then
Exit;
Dec(Top);
end;
end;
Result := Top = 0;
end;
begin
WriteLn('(a + b) * c -> ', IsBalanced('(a + b) * c'));
WriteLn('[a + (b * c)] -> ', IsBalanced('[a + (b * c)]'));
WriteLn('{a + (b] * c} -> ', IsBalanced('{a + (b] * c}'));
WriteLn('((a + b) -> ', IsBalanced('((a + b)'));
WriteLn('a + b) -> ', IsBalanced('a + b)'));
end.
Only brackets are examined; letters, operators, and spaces are skipped. The
mismatched pair {a + (b] * c} fails when the ] meets a
( on top of the stack. The unclosed ((a + b) leaves one
opening bracket on the stack, so the final test is false. The extra closing
bracket in a + b) is caught immediately because the stack is empty.
$ fpc -gl brackets.pas
$ ./brackets
(a + b) * c -> TRUE
[a + (b * c)] -> TRUE
{a + (b] * c} -> FALSE
((a + b) -> FALSE
a + b) -> FALSE
A circular queue
A queue needs a front and a back. In an array, removing the front element would
otherwise require shifting every remaining element. A circular queue avoids the
shift: the array is treated as a ring, and the head and tail indices wrap around
with mod Capacity. A separate count distinguishes a full queue from
an empty one, since both can have equal head and tail indices.
program circqueue;
{$mode objfpc}{$H+}
const
Capacity = 4;
type
TQueue = record
Items: array[0..Capacity - 1] of Integer;
Head, Tail, Count: Integer;
end;
procedure Init(var Q: TQueue);
begin
Q.Head := 0;
Q.Tail := 0;
Q.Count := 0;
end;
function IsFull(const Q: TQueue): Boolean;
begin
Result := Q.Count = Capacity;
end;
function IsEmpty(const Q: TQueue): Boolean;
begin
Result := Q.Count = 0;
end;
function Enqueue(var Q: TQueue; Value: Integer): Boolean;
begin
Result := not IsFull(Q);
if Result then
begin
Q.Items[Q.Tail] := Value;
Q.Tail := (Q.Tail + 1) mod Capacity;
Inc(Q.Count);
end;
end;
function Dequeue(var Q: TQueue; out Value: Integer): Boolean;
begin
Result := not IsEmpty(Q);
if Result then
begin
Value := Q.Items[Q.Head];
Q.Head := (Q.Head + 1) mod Capacity;
Dec(Q.Count);
end;
end;
var
Q: TQueue;
Value, I: Integer;
begin
Init(Q);
for I := 1 to 4 do
WriteLn('enqueue ', I * 10, ': ', Enqueue(Q, I * 10));
WriteLn('full: ', IsFull(Q));
WriteLn('enqueue 50: ', Enqueue(Q, 50));
Write('drain:');
while Dequeue(Q, Value) do
Write(' ', Value);
WriteLn;
WriteLn('empty: ', IsEmpty(Q));
for I := 5 to 8 do
WriteLn('enqueue ', I * 10, ': ', Enqueue(Q, I * 10));
end.
After four enqueues the tail has wrapped to 0 and the count equals the capacity,
so the fifth enqueue is refused. Draining the queue moves the head forward and
decreases the count; the slots themselves are not cleared, but they are
overwritten by the next enqueue. The second group of enqueues succeeds because
the queue is empty again. Enqueue and Dequeue report
success with a Boolean, so a full or empty queue never corrupts the indices.
$ fpc -gl circqueue.pas $ ./circqueue enqueue 10: TRUE enqueue 20: TRUE enqueue 30: TRUE enqueue 40: TRUE full: TRUE enqueue 50: FALSE drain: 10 20 30 40 empty: TRUE enqueue 50: TRUE enqueue 60: TRUE enqueue 70: TRUE enqueue 80: TRUE
A stack as an advanced record
The procedures from the previous sections can become methods of the record.
ObjFPC requires {$modeswitch advancedrecords} for methods, private
fields, and properties inside a record. The private section hides the array and
the index, so callers can only use the operations. This is encapsulation without
heap allocation: a record variable is still a value, copied field by field.
program recordstack;
{$mode objfpc}{$H+}
{$modeswitch advancedrecords}
const
MaxSize = 5;
type
TStack = record
private
FItems: array[1..MaxSize] of Integer;
FTop: Integer;
public
procedure Init;
function Push(Value: Integer): Boolean;
function Pop(out Value: Integer): Boolean;
function IsEmpty: Boolean;
function Count: Integer;
end;
procedure TStack.Init;
begin
FTop := 0;
end;
function TStack.Push(Value: Integer): Boolean;
begin
Result := FTop < MaxSize;
if Result then
begin
Inc(FTop);
FItems[FTop] := Value;
end;
end;
function TStack.Pop(out Value: Integer): Boolean;
begin
Result := FTop > 0;
if Result then
begin
Value := FItems[FTop];
Dec(FTop);
end;
end;
function TStack.IsEmpty: Boolean;
begin
Result := FTop = 0;
end;
function TStack.Count: Integer;
begin
Result := FTop;
end;
var
S: TStack;
Value: Integer;
begin
S.Init;
S.Push(10);
S.Push(20);
S.Push(30);
WriteLn('count = ', S.Count);
while S.Pop(Value) do
WriteLn('pop: ', Value);
WriteLn('empty: ', S.IsEmpty);
end.
S.Init sets the index, and the other methods work on the same
record. Count is a method rather than a property here, so the call
has parentheses. The success flags are unchanged: a full push or an empty pop
returns False. A method receives the record through an implicit
reference to Self, so S.Push modifies S;
passing S to a standalone procedure by value would copy the whole
array.
$ fpc -gl recordstack.pas $ ./recordstack count = 3 pop: 30 pop: 20 pop: 10 empty: TRUE
Generic stacks and queues
The Generics.Collections unit provides
TStack<T> and TQueue<T>, which grow as
needed and need no fixed capacity. The operations have the same names as the
ones above: Push, Pop, and Peek for the
stack, and Enqueue, Dequeue, and Peek
for the queue. These are classes, so they are created with Create
and released in a finally block.
program generic;
{$mode objfpc}{$H+}
uses Generics.Collections;
type
TIntStack = specialize TStack<Integer>;
TIntQueue = specialize TQueue<Integer>;
var
Stack: TIntStack;
Queue: TIntQueue;
Value: Integer;
begin
Stack := TIntStack.Create;
try
Stack.Push(10);
Stack.Push(20);
Stack.Push(30);
WriteLn('stack count = ', Stack.Count);
WriteLn('stack peek = ', Stack.Peek);
while Stack.Count > 0 do
WriteLn('stack pop: ', Stack.Pop);
finally
Stack.Free;
end;
Queue := TIntQueue.Create;
try
Queue.Enqueue(10);
Queue.Enqueue(20);
Queue.Enqueue(30);
WriteLn('queue count = ', Queue.Count);
WriteLn('queue peek = ', Queue.Peek);
while Queue.Count > 0 do
begin
Value := Queue.Dequeue;
WriteLn('queue pop: ', Value);
end;
finally
Queue.Free;
end;
end.
The stack prints 30, 20, 10 and the queue prints 10, 20, 30 from the same
insertion order. Peek returns the next element without removing it.
The specialize keyword is required in ObjFPC mode, as the
generics article explains. The standard classes
raise EArgumentOutOfRangeException on an empty pop, unlike the
Boolean-returning versions above; the
exceptions article shows how to catch them.
$ fpc -gl generic.pas $ ./generic stack count = 3 stack peek = 30 stack pop: 30 stack pop: 20 stack pop: 10 queue count = 3 queue peek = 10 queue pop: 10 queue pop: 20 queue pop: 30
Breadth-first search with a queue
A queue drives breadth-first search. The search starts at one cell, marks it as seen, and enqueues it with distance zero. Each dequeued cell examines its neighbours; unvisited cells that are not walls are marked and enqueued with a distance one larger. Because the queue is first in, first out, cells are processed in order of distance, so the first time the goal is dequeued its distance is the shortest path.
program bfs;
{$mode objfpc}{$H+}
const
Rows = 5;
Cols = 5;
Grid: array[0..Rows - 1, 0..Cols - 1] of Char = (
('S', '.', '.', '#', '.'),
('.', '#', '.', '#', '.'),
('.', '#', '.', '.', '.'),
('.', '.', '#', '#', '.'),
('#', '.', '.', '.', 'E'));
Dr: array[0..3] of Integer = (-1, 1, 0, 0);
Dc: array[0..3] of Integer = (0, 0, -1, 1);
type
TCell = record
Row, Col, Dist: Integer;
end;
function ShortestPath: Integer;
var
Queue: array[0..Rows * Cols - 1] of TCell;
Head, Tail: Integer;
Seen: array[0..Rows - 1, 0..Cols - 1] of Boolean;
Current: TCell;
R, C, I: Integer;
begin
FillChar(Seen, SizeOf(Seen), 0);
Head := 0;
Tail := 0;
Queue[Tail].Row := 0;
Queue[Tail].Col := 0;
Queue[Tail].Dist := 0;
Inc(Tail);
Seen[0, 0] := True;
Result := -1;
while Head < Tail do
begin
Current := Queue[Head];
Inc(Head);
if Grid[Current.Row, Current.Col] = 'E' then
Exit(Current.Dist);
for I := 0 to 3 do
begin
R := Current.Row + Dr[I];
C := Current.Col + Dc[I];
if (R >= 0) and (R < Rows) and (C >= 0) and (C < Cols) and
(not Seen[R, C]) and (Grid[R, C] <> '#') then
begin
Seen[R, C] := True;
Queue[Tail].Row := R;
Queue[Tail].Col := C;
Queue[Tail].Dist := Current.Dist + 1;
Inc(Tail);
end;
end;
end;
end;
begin
WriteLn('shortest path = ', ShortestPath, ' steps');
end.
The grid is five by five, S marks the start and E the
end, and # marks a wall. The queue array has room for every cell
because each cell is enqueued at most once. The four direction arrays
Dr and Dc encode up, down, left, and right, which
keeps the neighbour loop short. The shortest route takes eight steps.
$ fpc -gl bfs.pas $ ./bfs shortest path = 8 steps
Choosing an implementation
An array-based stack is the fastest and simplest choice when the maximum size
is known. A linked stack never overflows but allocates a node per push. The
generic TStack<T> grows automatically and is the usual choice
in application code. The same trade-offs apply to queues: a circular array is
compact and allocation-free, while a linked queue grows without a fixed
capacity.
Both structures are defined by their operations, not by their storage. A stack supports push, pop, peek, and count; a queue supports enqueue, dequeue, peek, and count. Any implementation that provides those operations can replace another without changing the algorithm that uses it, which is why the breadth-first search above would work with the generic queue as well.
Next steps
The linked lists article builds the node chains that a linked stack or queue uses, and the binary trees article uses a queue for level-order traversal. The generics article explains the container types in more detail, and the sorting article uses stacks implicitly in its recursive algorithms.
Source
Free Pascal Run-Time Library reference
In this article we built a stack from an array and a top index, wrapped push and pop in Boolean-returning procedures, matched brackets with it, implemented a circular queue, encapsulated the stack in an advanced record, used the generic stack and queue classes, and drove a breadth-first search with a queue. The series continues with binary trees in Pascal.
Author
List all Pascal tutorials.