A generic stack package can be implemented in the Ada programming language using a linked list data structure. Each item points to the next entry in the stack.
generic_stack.ads
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
with Ada.Unchecked_Deallocation;
generic
type Element_Type is private;
package Generic_Stack is
type Stack is private;
procedure Push (S : in out Stack; Item : Element_Type);
function Pop (S : in out Stack) return Element_Type;
function Empty(S: Stack) return Boolean;
procedure Free (S : in out Stack);
Empty_Stack : exception;
private
type Node;
type Stack is access Node;
type Node is record
Value : Element_Type;
Next : Stack;
end record;
procedure Free_Node is new Ada.Unchecked_Deallocation (Node, Stack);
end Generic_Stack;
|
generic_stack.adb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
package body Generic_Stack is
procedure Push (S : in out Stack; Item : Element_Type) is
begin
S := new Node'(Item, S);
end Push;
function Pop (S : in out Stack) return Element_Type is
Head : Stack := S;
Result : Element_Type;
begin
if Head = null then
raise Empty_Stack;
end if;
Result := Head.Value;
S := Head.Next;
Free_Node (Head);
return Result;
end Pop;
function Empty(S: Stack) return Boolean is
begin
return S = null;
end Empty;
function Top (S : Stack) return Element_Type is
Head : Stack := S;
begin
if Head = null then
raise Empty_Stack;
end if;
return Head.Value;
end Top;
procedure Free (S : in out Stack) is
Current : Stack;
begin
while S /= null loop
Current := S;
S := S.Next;
Free_Node (Current);
end loop;
end Free;
end Generic_Stack;
|