Ada stacks, queues and trees
last modified November 23, 2026
A stack, a queue, and a tree all store their elements in nodes connected by access values, but they connect them differently. A stack adds and removes at one end, a queue adds at one end and removes at the other, and a tree branches into two. This article builds all three from the node pattern used by the linked list, makes the stack generic, and closes with a bracket checker that uses a stack of characters.
A stack of linked nodes
A stack is last in, first out: the most recently pushed value is the first one
popped. The node type is the same as in a linked list, and Stack
only needs a Top pointer. Push allocates a node whose
Next is the old top, and Pop reads the value before
freeing the node.
with Ada.Text_IO;
with Ada.Unchecked_Deallocation;
use Ada.Text_IO;
procedure Stack_Demo is
type Node;
type Node_Ptr is access Node;
type Node is record
Value : Integer;
Next : Node_Ptr := null;
end record;
type Stack is record
Top : Node_Ptr := null;
end record;
procedure Free is new Ada.Unchecked_Deallocation (Node, Node_Ptr);
procedure Push (S : in out Stack; Value : Integer) is
begin
S.Top := new Node'(Value, S.Top);
end Push;
procedure Pop (S : in out Stack; Value : out Integer) is
Old : Node_Ptr := S.Top;
begin
Value := Old.Value;
S.Top := Old.Next;
Free (Old);
end Pop;
S : Stack;
V : Integer;
begin
for I in 1 .. 3 loop
Push (S, I * 10);
end loop;
while S.Top /= null loop
Pop (S, V);
Put_Line ("pop" & Integer'Image (V));
end loop;
end Stack_Demo;
The values go on as 10, 20, 30 and come off as 30, 20, 10. Pop
assumes that the stack is not empty; the loop tests S.Top before
each call. A library version should either test inside Pop or raise
an exception when the stack is empty.
$ gnatmake -gnat2022 -gnatwa stack_demo.adb $ ./stack_demo pop 30 pop 20 pop 10
A generic stack package
The package takes the element type as a formal private type, so one body serves
integers, characters, records, and anything else that can be stored in a
component. Pop raises Constraint_Error with a message
on an empty stack, and Depth returns the stored count without
walking the chain.
generic
type Element_Type is private;
package Stacks is
type Stack is limited private;
procedure Push (S : in out Stack; Value : Element_Type);
procedure Pop (S : in out Stack; Value : out Element_Type);
function Is_Empty (S : Stack) return Boolean;
function Depth (S : Stack) return Natural;
procedure Clear (S : in out Stack);
private
type Node;
type Node_Ptr is access Node;
type Node is record
Value : Element_Type;
Next : Node_Ptr := null;
end record;
type Stack is limited record
Top : Node_Ptr := null;
Size : Natural := 0;
end record;
end Stacks;
The private part stores the top pointer and a size. The node type names
Element_Type, which the compiler replaces with the actual type at
each instantiation. Nothing in the specification exposes the nodes, so a client
cannot create a node or link one into the stack by hand. The stack type is
limited, which prevents an assignment from copying the top pointer and making
two stacks free the same chain.
with Ada.Unchecked_Deallocation;
package body Stacks is
procedure Free is new Ada.Unchecked_Deallocation (Node, Node_Ptr);
procedure Push (S : in out Stack; Value : Element_Type) is
begin
S.Top := new Node'(Value, S.Top);
S.Size := S.Size + 1;
end Push;
procedure Pop (S : in out Stack; Value : out Element_Type) is
Old : Node_Ptr := S.Top;
begin
if Old = null then
raise Constraint_Error with "pop from empty stack";
end if;
Value := Old.Value;
S.Top := Old.Next;
S.Size := S.Size - 1;
Free (Old);
end Pop;
function Is_Empty (S : Stack) return Boolean is (S.Top = null);
function Depth (S : Stack) return Natural is (S.Size);
procedure Clear (S : in out Stack) is
P : Node_Ptr := S.Top;
Next : Node_Ptr;
begin
while P /= null loop
Next := P.Next;
Free (P);
P := Next;
end loop;
S.Top := null;
S.Size := 0;
end Clear;
end Stacks;
Pop checks for null before dereferencing Old, which
turns an empty pop into a clear exception instead of a memory fault.
Clear is the same loop as in the list package: save the next
pointer, free the current node, and move on. The size is decremented in
Pop and reset in Clear.
with Ada.Text_IO;
with Stacks;
use Ada.Text_IO;
procedure Stack_Main is
package Int_Stacks is new Stacks (Integer);
use Int_Stacks;
S : Stack;
V : Integer;
begin
Push (S, 10);
Push (S, 20);
Push (S, 30);
Put_Line ("depth =" & Integer'Image (Depth (S)));
while not Is_Empty (S) loop
Pop (S, V);
Put_Line ("pop" & Integer'Image (V));
end loop;
end Stack_Main;
The instantiation creates a package named Int_Stacks, and the
use clause makes its operations directly visible. The same
Stacks generic is instantiated again for Character at
the end of the article. The bounded array stack from the
generics article has a fixed capacity; this one
grows with each push.
$ gnatmake -gnat2022 -gnatwa stack_main.adb $ ./stack_main depth = 3 pop 30 pop 20 pop 10
A queue with head and tail
A queue is first in, first out. Enqueue adds at the tail and
Dequeue removes from the head, so the oldest value leaves first.
Both ends need a pointer: without Tail, every enqueue would have to
walk the whole chain.
with Ada.Text_IO;
with Ada.Unchecked_Deallocation;
use Ada.Text_IO;
procedure Queue_Demo is
type Node;
type Node_Ptr is access Node;
type Node is record
Value : Integer;
Next : Node_Ptr := null;
end record;
type Queue is record
Head : Node_Ptr := null;
Tail : Node_Ptr := null;
end record;
procedure Free is new Ada.Unchecked_Deallocation (Node, Node_Ptr);
procedure Enqueue (Q : in out Queue; Value : Integer) is
New_Node : constant Node_Ptr := new Node'(Value, null);
begin
if Q.Tail = null then
Q.Head := New_Node;
else
Q.Tail.Next := New_Node;
end if;
Q.Tail := New_Node;
end Enqueue;
procedure Dequeue (Q : in out Queue; Value : out Integer) is
Old : Node_Ptr := Q.Head;
begin
Value := Old.Value;
Q.Head := Old.Next;
if Q.Head = null then
Q.Tail := null;
end if;
Free (Old);
end Dequeue;
procedure Clear (Q : in out Queue) is
P : Node_Ptr := Q.Head;
Next : Node_Ptr;
begin
while P /= null loop
Next := P.Next;
Free (P);
P := Next;
end loop;
Q.Head := null;
Q.Tail := null;
end Clear;
Q : Queue;
V : Integer;
begin
for I in 1 .. 4 loop
Enqueue (Q, I * 10);
end loop;
while Q.Head /= null loop
Dequeue (Q, V);
Put_Line ("serve" & Integer'Image (V));
end loop;
Clear (Q);
end Queue_Demo;
When the last node is removed, both Head and Tail must
become null; otherwise the next enqueue would attach a node to a freed tail.
The stack and the queue share the node shape, but the order of removal is the
whole difference: the stack removes at the top, the queue at the head.
$ gnatmake -gnat2022 -gnatwa queue_demo.adb $ ./queue_demo serve 10 serve 20 serve 30 serve 40
A binary search tree
A binary search tree keeps every smaller value in the left subtree and every
larger value in the right subtree. Insert follows that rule until
it finds a null child and allocates the node there. An in-order traversal visits
the left subtree, the node, and the right subtree, which prints the values in
sorted order.
with Ada.Text_IO;
with Ada.Unchecked_Deallocation;
use Ada.Text_IO;
procedure Tree_Demo is
type Node;
type Node_Ptr is access Node;
type Node is record
Value : Integer;
Left : Node_Ptr := null;
Right : Node_Ptr := null;
end record;
procedure Free is new Ada.Unchecked_Deallocation (Node, Node_Ptr);
procedure Insert (Root : in out Node_Ptr; Value : Integer) is
begin
if Root = null then
Root := new Node'(Value, null, null);
elsif Value < Root.Value then
Insert (Root.Left, Value);
elsif Value > Root.Value then
Insert (Root.Right, Value);
end if;
end Insert;
procedure Print_In_Order (Root : Node_Ptr) is
begin
if Root /= null then
Print_In_Order (Root.Left);
Put (Integer'Image (Root.Value));
Print_In_Order (Root.Right);
end if;
end Print_In_Order;
procedure Clear (Root : in out Node_Ptr) is
begin
if Root /= null then
Clear (Root.Left);
Clear (Root.Right);
Free (Root);
end if;
end Clear;
type Values is array (Positive range <>) of Integer;
Data : constant Values := [50, 30, 70, 20, 40, 60, 80, 35];
Root : Node_Ptr := null;
begin
for V of Data loop
Insert (Root, V);
end loop;
Print_In_Order (Root);
New_Line;
Clear (Root);
end Tree_Demo;
The root is 50, so 30 goes left and 70 goes right; 35 travels left to 30,
right to 40, and finally left again. The in-order output is completely sorted
even though the insertion order was not. A value equal to the current node is
ignored because neither branch is taken, so the tree holds each distinct value
once. Clear frees the children before the parent, because the
parent still needs its child pointers to find them.
$ gnatmake -gnat2022 -gnatwa tree_demo.adb $ ./tree_demo 20 30 35 40 50 60 70 80
Searching the tree and measuring its height
The same ordering that guides insertion also guides a lookup. Contains
compares the value with the current node and follows one child, so a balanced
tree needs only a handful of comparisons. Height is the number of
nodes on the longest path from the root to a leaf.
function Contains (Root : Node_Ptr; Value : Integer) return Boolean is
begin
if Root = null then
return False;
elsif Root.Value = Value then
return True;
elsif Value < Root.Value then
return Contains (Root.Left, Value);
else
return Contains (Root.Right, Value);
end if;
end Contains;
function Height (Root : Node_Ptr) return Natural is
begin
if Root = null then
return 0;
else
return 1 + Natural'Max (Height (Root.Left), Height (Root.Right));
end if;
end Height;
Contains has two base cases: a null child means the value is
absent, and an equal value means it is present. Height returns zero
for an empty subtree and otherwise adds one to the taller of its two children.
The tree in the previous section has height four, along the path
50 -> 30 -> 40 -> 35.
begin
for V of Data loop
Insert (Root, V);
end loop;
Put_Line ("contains 40 =" & Boolean'Image (Contains (Root, 40)));
Put_Line ("contains 45 =" & Boolean'Image (Contains (Root, 45)));
Put_Line ("height =" & Integer'Image (Height (Root)));
Clear (Root);
end Tree_Ops;
The other declarations from tree_demo.adb are unchanged; only the
two functions and the statements that call them are new. A search for 45 ends at
a null child and reports false, while 40 is found after three comparisons.
$ gnatmake -gnat2022 -gnatwa tree_ops.adb $ ./tree_ops contains 40 =TRUE contains 45 =FALSE height = 4
An applied example: balanced brackets
A stack is the natural tool for nested brackets. Every opening bracket is
pushed; every closing bracket must match the one on top of the stack. If a
mismatch occurs, or the stack is not empty at the end, the text is not balanced.
The program instantiates the generic stack with Character.
with Ada.Text_IO;
with Stacks;
use Ada.Text_IO;
procedure Balanced is
package Char_Stacks is new Stacks (Character);
use Char_Stacks;
function Is_Balanced (Text : String) return Boolean is
S : Stack;
C : Character;
OK : Boolean := True;
begin
for Ch of Text loop
case Ch is
when '(' | '[' =>
Push (S, Ch);
when ')' =>
if Is_Empty (S) then
OK := False;
else
Pop (S, C);
OK := OK and then C = '(';
end if;
when ']' =>
if Is_Empty (S) then
OK := False;
else
Pop (S, C);
OK := OK and then C = '[';
end if;
when others =>
null;
end case;
exit when not OK;
end loop;
if not OK then
return False;
end if;
return Is_Empty (S);
end Is_Balanced;
begin
Put_Line ("(a [b] c) =" & Boolean'Image (Is_Balanced ("(a [b] c)")));
Put_Line ("([a) b] =" & Boolean'Image (Is_Balanced ("([a) b]")));
end Balanced;
The first string nests a square pair inside a round pair, so both pushes are
matched and the stack ends empty. The second string closes the round bracket
while a square bracket is on top, so C = '(' is false and the
function reports failure. Characters other than brackets are ignored by the
others branch.
$ gnatmake -gnat2022 -gnatwa balanced.adb $ ./balanced (a [b] c) =TRUE ([a) b] =FALSE
Next steps
The next article looks up values by key instead of by position. It hashes a string, resolves collisions with open addressing, grows the table when it gets full, and compares the result with the standard hashed map. The linked lists article explains the node and freeing patterns that all three structures in this article reuse.
Source
In this article we have built a linked stack, made it generic over the element type, built a queue with head and tail pointers, inserted values into a binary search tree and printed them in order, searched the tree and measured its height, and checked nested brackets with a stack of characters. The generics article explains the formal type and the instantiation used by the stack package.
Author
List all Ada tutorials.