Modula-2 stacks, queues and trees
last modified November 27, 2026 Modula-2
A stack, a queue and a tree are built from the same nodes as a linked list, but each allows only a few operations. That makes them good candidates for abstract data types: a definition module declares an opaque type and its operations, and the nodes stay hidden in the implementation module. A client cannot break the structure, and the implementation can change without touching the client.
All examples are compiled with -fiso. Each module is compiled
once with -c and linked with the programs that use it.
A stack
A stack gives back its values in the reverse order: the last value pushed is the first one popped. The definition module lists the operations and nothing else.
DEFINITION MODULE Stacks; TYPE Stack; PROCEDURE Create(): Stack; PROCEDURE Push(s: Stack; value: INTEGER); PROCEDURE Pop(s: Stack): INTEGER; PROCEDURE IsEmpty(s: Stack): BOOLEAN; PROCEDURE Destroy(VAR s: Stack); END Stacks.
Stack is opaque. Create makes an empty stack,
Push and Pop add and remove the top value, and
Destroy frees the stack and everything in it.
IMPLEMENTATION MODULE Stacks;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
Link = POINTER TO Node;
Node = RECORD
value: INTEGER;
next: Link
END;
Stack = POINTER TO RECORD
top: Link
END;
PROCEDURE Create(): Stack;
VAR
s: Stack;
BEGIN
NEW(s);
s^.top := NIL;
RETURN s
END Create;
PROCEDURE Push(s: Stack; value: INTEGER);
VAR
p: Link;
BEGIN
NEW(p);
p^.value := value;
p^.next := s^.top;
s^.top := p
END Push;
PROCEDURE Pop(s: Stack): INTEGER;
VAR
p: Link;
value: INTEGER;
BEGIN
p := s^.top;
value := p^.value;
s^.top := p^.next;
DISPOSE(p);
RETURN value
END Pop;
PROCEDURE IsEmpty(s: Stack): BOOLEAN;
BEGIN
RETURN s^.top = NIL
END IsEmpty;
PROCEDURE Destroy(VAR s: Stack);
VAR
value: INTEGER;
BEGIN
WHILE NOT IsEmpty(s) DO
value := Pop(s)
END;
DISPOSE(s)
END Destroy;
END Stacks.
The implementation keeps a linked list of nodes; the top of the stack is
the first node, so both Push and Pop work at the
front of the list and never walk it. Stack is a pointer to a
record that holds the list. Because the record is on the heap and the
procedures only change its field, Push and Pop
take the stack as a value parameter. Pop on an empty stack
dereferences NIL and aborts the program, so the caller tests
IsEmpty first.
MODULE bases;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM Stacks IMPORT Stack, Create, Push, Pop, IsEmpty, Destroy;
CONST
Digits = "0123456789ABCDEF";
PROCEDURE WriteBase(n, base: CARDINAL);
VAR
s: Stack;
digits: ARRAY [0..15] OF CHAR;
BEGIN
digits := Digits;
s := Create();
REPEAT
Push(s, INTEGER(n MOD base));
n := n DIV base
UNTIL n = 0;
WHILE NOT IsEmpty(s) DO
WriteChar(digits[Pop(s)])
END;
Destroy(s)
END WriteBase;
VAR
year: CARDINAL;
BEGIN
year := 2026;
WriteCard(year, 0); WriteString(" = ");
WriteBase(year, 2); WriteString(" (2) = ");
WriteBase(year, 8); WriteString(" (8) = ");
WriteBase(year, 16); WriteString(" (16)");
WriteLn
END bases.
The client writes a number in several bases. Dividing by the base produces the digits from the last to the first; the stack turns them round. The digit is used as an index into a string of digit characters. The program does not know how the stack is built; it uses only the five procedures.
$ gm2 -fiso -c Stacks.mod $ gm2 -fiso bases.mod Stacks.o -o bases $ ./bases 2026 = 11111101010 (2) = 3752 (8) = 7EA (16)
Matching brackets
A stack remembers what is still open. A text has balanced brackets when every closing bracket matches the most recent bracket that is still open.
MODULE brackets;
FROM STextIO IMPORT WriteString, WriteLn;
FROM Stacks IMPORT Stack, Create, Push, Pop, IsEmpty, Destroy;
PROCEDURE Balanced(text: ARRAY OF CHAR): BOOLEAN;
VAR
s: Stack;
i: CARDINAL;
ch, open: CHAR;
ok: BOOLEAN;
BEGIN
s := Create();
ok := TRUE;
i := 0;
WHILE ok AND (i <= HIGH(text)) AND (text[i] # 0C) DO
ch := text[i];
IF (ch = '(') OR (ch = '[') OR (ch = '{') THEN
Push(s, ORD(ch))
ELSIF (ch = ')') OR (ch = ']') OR (ch = '}') THEN
IF IsEmpty(s) THEN
ok := FALSE
ELSE
open := CHR(Pop(s));
ok := ((open = '(') AND (ch = ')')) OR
((open = '[') AND (ch = ']')) OR
((open = '{') AND (ch = '}'))
END
END;
INC(i)
END;
ok := ok AND IsEmpty(s);
Destroy(s);
RETURN ok
END Balanced;
PROCEDURE Check(text: ARRAY OF CHAR);
BEGIN
WriteString(text);
IF Balanced(text) THEN
WriteString(" balanced")
ELSE
WriteString(" not balanced")
END;
WriteLn
END Check;
BEGIN
Check("a[i] := (b + c) * d");
Check("{(x + 1) * [y - 2]}");
Check("(a + b]");
Check("((a + b)");
Check("a + b)")
END brackets.
Each opening bracket is pushed; the stack holds integers, so the character
goes in as its ORD and comes back with CHR. A
closing bracket pops the last opening one and checks that the two form a
pair. The text is unbalanced when a closing bracket finds the stack empty,
when the pair does not match, or when some brackets are still open at the
end. Destroy frees what is left on the stack in every case.
$ gm2 -fiso brackets.mod Stacks.o -o brackets
$ ./brackets
a[i] := (b + c) * d balanced
{(x + 1) * [y - 2]} balanced
(a + b] not balanced
((a + b) not balanced
a + b) not balanced
A queue
A queue gives back its values in the order in which they arrived. Values are added at the end and removed from the front, so the implementation keeps a pointer to both ends of the list.
DEFINITION MODULE Queues; TYPE Queue; PROCEDURE Create(): Queue; PROCEDURE Enqueue(q: Queue; value: INTEGER); PROCEDURE Dequeue(q: Queue): INTEGER; PROCEDURE IsEmpty(q: Queue): BOOLEAN; PROCEDURE Length(q: Queue): CARDINAL; PROCEDURE Destroy(VAR q: Queue); END Queues.
The interface resembles the stack: Enqueue adds a value at
the end, Dequeue removes the first one, and
Length tells how many values wait.
IMPLEMENTATION MODULE Queues;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
Link = POINTER TO Node;
Node = RECORD
value: INTEGER;
next: Link
END;
Queue = POINTER TO RECORD
first, last: Link;
count: CARDINAL
END;
PROCEDURE Create(): Queue;
VAR
q: Queue;
BEGIN
NEW(q);
q^.first := NIL;
q^.last := NIL;
q^.count := 0;
RETURN q
END Create;
PROCEDURE Enqueue(q: Queue; value: INTEGER);
VAR
p: Link;
BEGIN
NEW(p);
p^.value := value;
p^.next := NIL;
IF q^.last = NIL THEN
q^.first := p
ELSE
q^.last^.next := p
END;
q^.last := p;
INC(q^.count)
END Enqueue;
PROCEDURE Dequeue(q: Queue): INTEGER;
VAR
p: Link;
value: INTEGER;
BEGIN
p := q^.first;
value := p^.value;
q^.first := p^.next;
IF q^.first = NIL THEN
q^.last := NIL
END;
DISPOSE(p);
DEC(q^.count);
RETURN value
END Dequeue;
PROCEDURE IsEmpty(q: Queue): BOOLEAN;
BEGIN
RETURN q^.first = NIL
END IsEmpty;
PROCEDURE Length(q: Queue): CARDINAL;
BEGIN
RETURN q^.count
END Length;
PROCEDURE Destroy(VAR q: Queue);
VAR
value: INTEGER;
BEGIN
WHILE NOT IsEmpty(q) DO
value := Dequeue(q)
END;
DISPOSE(q)
END Destroy;
END Queues.
Enqueue links the new node after last, or makes
it the first node when the queue is empty. Dequeue takes the
first node; when it was the only one, last is reset to
NIL as well. The record also keeps a count, so
Length does not walk the list. Both ends are reached directly,
and every operation takes the same time regardless of the length of the
queue.
MODULE rounds;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt, WriteCard;
FROM Queues IMPORT Queue, Create, Enqueue, Dequeue, IsEmpty, Length, Destroy;
CONST
Tasks = 4;
Slice = 3;
VAR
work: ARRAY [1..Tasks] OF INTEGER;
ready: Queue;
task, clock: INTEGER;
BEGIN
work[1] := 5; work[2] := 2; work[3] := 7; work[4] := 3;
ready := Create();
FOR task := 1 TO Tasks DO
Enqueue(ready, task)
END;
clock := 0;
WHILE NOT IsEmpty(ready) DO
task := Dequeue(ready);
IF work[task] > Slice THEN
INC(clock, Slice);
DEC(work[task], Slice);
Enqueue(ready, task)
ELSE
INC(clock, work[task]);
work[task] := 0;
WriteString("time"); WriteInt(clock, 3);
WriteString(": task"); WriteInt(task, 2);
WriteString(" done, waiting: "); WriteCard(Length(ready), 0);
WriteLn
END
END;
Destroy(ready)
END rounds.
The client simulates round-robin scheduling. Four tasks need 5, 2, 7 and 3 units of work. The scheduler takes the first task from the queue and lets it run for at most three units; a task that is not finished goes back to the end of the queue. The program prints the time at which each task completes.
$ gm2 -fiso -c Queues.mod $ gm2 -fiso rounds.mod Queues.o -o rounds $ ./rounds time 5: task 2 done, waiting: 3 time 11: task 4 done, waiting: 2 time 13: task 1 done, waiting: 1 time 17: task 3 done, waiting: 0
Two modules with the same names
Both modules export Create, IsEmpty and
Destroy. A program that uses both cannot import these names
with FROM; it imports the modules and writes qualified names.
MODULE turn;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
IMPORT Stacks, Queues;
PROCEDURE Show(label: ARRAY OF CHAR; q: Queues.Queue);
VAR
i, n: CARDINAL;
value: INTEGER;
BEGIN
WriteString(label);
n := Queues.Length(q);
FOR i := 1 TO n DO
value := Queues.Dequeue(q);
WriteInt(value, 3);
Queues.Enqueue(q, value)
END;
WriteLn
END Show;
VAR
line: Queues.Queue;
pile: Stacks.Stack;
k: INTEGER;
BEGIN
line := Queues.Create();
FOR k := 1 TO 8 DO
Queues.Enqueue(line, k * 11)
END;
Show("queue: ", line);
pile := Stacks.Create();
WHILE NOT Queues.IsEmpty(line) DO
Stacks.Push(pile, Queues.Dequeue(line))
END;
WHILE NOT Stacks.IsEmpty(pile) DO
Queues.Enqueue(line, Stacks.Pop(pile))
END;
Show("reversed:", line);
Stacks.Destroy(pile);
Queues.Destroy(line)
END turn.
IMPORT Stacks, Queues makes the module names visible, and
every use is written as Queues.Create or
Stacks.Pop. The program reverses a queue: it moves every value
to a stack and then back to the queue. Show prints the queue
without destroying it; it dequeues each value and enqueues it again, so
after Length steps the queue is in its original order.
$ gm2 -fiso turn.mod Stacks.o Queues.o -o turn $ ./turn queue: 11 22 33 44 55 66 77 88 reversed: 88 77 66 55 44 33 22 11
A binary search tree
In a binary search tree each node has two subtrees: the left one holds smaller values and the right one larger values. Before it becomes a module, the tree is shown as a single program.
MODULE tree;
FROM STextIO IMPORT WriteLn;
FROM SWholeIO IMPORT WriteInt;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
Tree = POINTER TO Node;
Node = RECORD
value: INTEGER;
left, right: Tree
END;
PROCEDURE Insert(VAR t: Tree; value: INTEGER);
BEGIN
IF t = NIL THEN
NEW(t);
t^.value := value;
t^.left := NIL;
t^.right := NIL
ELSIF value < t^.value THEN
Insert(t^.left, value)
ELSIF value > t^.value THEN
Insert(t^.right, value)
END
END Insert;
PROCEDURE Walk(t: Tree);
BEGIN
IF t # NIL THEN
Walk(t^.left);
WriteInt(t^.value, 4);
Walk(t^.right)
END
END Walk;
PROCEDURE Free(VAR t: Tree);
BEGIN
IF t # NIL THEN
Free(t^.left);
Free(t^.right);
DISPOSE(t)
END
END Free;
VAR
root: Tree;
BEGIN
root := NIL;
Insert(root, 50); Insert(root, 30); Insert(root, 70);
Insert(root, 20); Insert(root, 40); Insert(root, 60);
Insert(root, 80); Insert(root, 30); Insert(root, 65);
Walk(root);
WriteLn;
Free(root)
END tree.
Insert descends to the left or right until it reaches an
empty subtree, and puts the new node there. The parameter is a
VAR parameter, so NEW(t) stores the node directly
in the parent's left or right field. A value that
is already in the tree is ignored, so the second 30 adds nothing.
Walk visits the left subtree, the node and the right subtree,
which prints the values in sorted order. Free must dispose of
both subtrees before the node that points to them.
$ gm2 -fiso tree.mod -o tree $ ./tree 20 30 40 50 60 65 70 80
A tree module
The tree moves into a module with an opaque type. This time the opaque
type is the pointer to the root node itself, and the empty tree is
NIL.
DEFINITION MODULE Trees; TYPE Tree; PROCEDURE Empty(): Tree; PROCEDURE Insert(VAR t: Tree; value: INTEGER); PROCEDURE Contains(t: Tree; value: INTEGER): BOOLEAN; PROCEDURE Height(t: Tree): CARDINAL; PROCEDURE Destroy(VAR t: Tree); END Trees.
Insert and Destroy change the root, so they take
a VAR parameter. Empty gives the client an empty
tree without revealing that it is NIL.
IMPLEMENTATION MODULE Trees;
FROM Storage IMPORT ALLOCATE, DEALLOCATE;
TYPE
Tree = POINTER TO Node;
Node = RECORD
value: INTEGER;
left, right: Tree
END;
PROCEDURE Empty(): Tree;
BEGIN
RETURN NIL
END Empty;
PROCEDURE Insert(VAR t: Tree; value: INTEGER);
BEGIN
IF t = NIL THEN
NEW(t);
t^.value := value;
t^.left := NIL;
t^.right := NIL
ELSIF value < t^.value THEN
Insert(t^.left, value)
ELSIF value > t^.value THEN
Insert(t^.right, value)
END
END Insert;
PROCEDURE Contains(t: Tree; value: INTEGER): BOOLEAN;
BEGIN
WHILE (t # NIL) AND (t^.value # value) DO
IF value < t^.value THEN
t := t^.left
ELSE
t := t^.right
END
END;
RETURN t # NIL
END Contains;
PROCEDURE Height(t: Tree): CARDINAL;
VAR
l, r: CARDINAL;
BEGIN
IF t = NIL THEN
RETURN 0
END;
l := Height(t^.left);
r := Height(t^.right);
IF l > r THEN
RETURN l + 1
END;
RETURN r + 1
END Height;
PROCEDURE Destroy(VAR t: Tree);
BEGIN
IF t # NIL THEN
Destroy(t^.left);
Destroy(t^.right);
DISPOSE(t)
END
END Destroy;
END Trees.
Insert and Destroy are the procedures of the
previous section. Contains needs no recursion: it follows one
path from the root, left or right, until it finds the value or falls off
the tree. Height is the number of nodes on the longest path
from the root down, one more than the height of the higher subtree.
MODULE lookup;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt, WriteCard;
FROM Trees IMPORT Tree, Empty, Insert, Contains, Height, Destroy;
VAR
primes: Tree;
n: INTEGER;
d: INTEGER;
prime: BOOLEAN;
BEGIN
primes := Empty();
FOR n := 2 TO 50 DO
prime := TRUE;
d := 2;
WHILE prime AND (d * d <= n) DO
prime := n MOD d # 0;
INC(d)
END;
IF prime THEN
Insert(primes, n)
END
END;
WriteString("height: "); WriteCard(Height(primes), 0); WriteLn;
FOR n := 40 TO 50 DO
WriteInt(n, 3);
IF Contains(primes, n) THEN
WriteString(" prime")
END;
WriteLn
END;
Destroy(primes)
END lookup.
The client stores the primes up to 50 and looks up the numbers from 40 to 50. Looking a value up costs at most as many steps as the tree is high. The height is 15, which is the number of primes: they were inserted in increasing order, so every node went to the right of the previous one and the tree is a linked list.
$ gm2 -fiso -c Trees.mod $ gm2 -fiso lookup.mod Trees.o -o lookup $ ./lookup height: 15 40 41 prime 42 43 prime 44 45 46 47 prime 48 49 50
The shape of the tree
The order of insertion decides the shape of the tree. The program inserts the numbers 1 to 127 in three different orders and prints the height of each tree.
MODULE shape;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM Trees IMPORT Tree, Empty, Insert, Height, Destroy;
CONST
N = 127;
PROCEDURE Report(label: ARRAY OF CHAR; VAR t: Tree);
BEGIN
WriteString(label);
WriteString(" height ");
WriteCard(Height(t), 3);
WriteLn;
Destroy(t)
END Report;
PROCEDURE Middle(VAR t: Tree; lo, hi: INTEGER);
VAR
mid: INTEGER;
BEGIN
IF lo <= hi THEN
mid := (lo + hi) DIV 2;
Insert(t, mid);
Middle(t, lo, mid - 1);
Middle(t, mid + 1, hi)
END
END Middle;
VAR
numbers: Tree;
i: INTEGER;
BEGIN
numbers := Empty();
FOR i := 1 TO N DO
Insert(numbers, i)
END;
Report("sorted: ", numbers);
numbers := Empty();
FOR i := 0 TO N - 1 DO
Insert(numbers, i * 37 MOD N + 1)
END;
Report("mixed: ", numbers);
numbers := Empty();
Middle(numbers, 1, N);
Report("middles: ", numbers)
END shape.
In sorted order the tree degenerates into a chain of 127 nodes. The mixed
order i * 37 MOD 127 + 1 visits every number once in a
scattered order and gives a height of 13. Middle inserts the
middle value of a range before the two halves, which produces a perfectly
balanced tree of 7 levels: 27 − 1 = 127. A lookup in that
tree takes at most seven steps, like a binary search in a sorted array.
Balanced trees, such as AVL trees, rearrange the nodes on insertion to stay
close to that height.
$ gm2 -fiso shape.mod Trees.o -o shape $ ./shape sorted: height 127 mixed: height 13 middles: height 7
Which structure to use
A stack fits work that has to be undone or finished in the reverse order: nested brackets, recursion replaced by a loop, undo histories. A queue fits work that is served in the order of arrival: tasks, messages, the nodes of a breadth-first search. A binary search tree keeps values sorted while they are inserted and finds them quickly, as long as it stays balanced. All three hide their nodes behind an opaque type, so a client cannot corrupt the links, and the implementation could switch to an array without a change in the client.
Source
Niklaus Wirth: Algorithms and Data Structures
In this article we have built a stack, a queue and a binary search tree as abstract data types with opaque types, used the stack for number bases and bracket matching and the queue for round-robin scheduling, imported two modules with clashing names qualified, and measured the height of search trees. The linked lists article covers the nodes, the opaque types article the hiding, and the hash tables article another way to find values quickly.
Author
List all Modula-2 tutorials.