summaryrefslogtreecommitdiff
path: root/stack/src
diff options
context:
space:
mode:
Diffstat (limited to 'stack/src')
-rw-r--r--stack/src/main.adb20
-rw-r--r--stack/src/stack.adb31
-rw-r--r--stack/src/stack.ads26
3 files changed, 77 insertions, 0 deletions
diff --git a/stack/src/main.adb b/stack/src/main.adb
new file mode 100644
index 0000000..977a46b
--- /dev/null
+++ b/stack/src/main.adb
@@ -0,0 +1,20 @@
1with Ada.Assertions; use Ada.Assertions;
2with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
3with Ada.Text_IO; use Ada.Text_IO;
4
5with Stack;
6
7procedure Main is
8 package IntStack is new Stack (Integer);
9 S : IntStack.Stack;
10 Val : Integer;
11begin
12 Put_Line ("Hello world!");
13 for I in 1 .. 5 loop
14 IntStack.Push (S, I);
15 end loop;
16 while not IntStack.Empty (S) loop
17 Assert (IntStack.Pop (S, Val));
18 Put_Line (Val'Image);
19 end loop;
20end Main;
diff --git a/stack/src/stack.adb b/stack/src/stack.adb
new file mode 100644
index 0000000..4dc8fb1
--- /dev/null
+++ b/stack/src/stack.adb
@@ -0,0 +1,31 @@
1with Ada.Unchecked_Deallocation;
2
3package body Stack is
4 procedure Free is new Ada.Unchecked_Deallocation (Node, Node_Access);
5
6 procedure Push (S : in out Stack; Val : T) is
7 New_Top : Node_Access := new Node;
8 begin
9 New_Top.Val := Val;
10 New_Top.Bottom := S.Top;
11 S.Top := New_Top;
12 end Push;
13
14 function Pop (S : in out Stack; Val : out T) return Boolean is
15 Old_Top : Node_Access := S.Top;
16 begin
17 if Old_Top /= null then
18 Val := Old_Top.Val;
19 S.Top := Old_Top.Bottom;
20 Free (Old_Top);
21 return True;
22 else
23 return False;
24 end if;
25 end Pop;
26
27 function Empty (S : Stack) return Boolean is
28 begin
29 return S.Top = null;
30 end Empty;
31end Stack;
diff --git a/stack/src/stack.ads b/stack/src/stack.ads
new file mode 100644
index 0000000..4f390e3
--- /dev/null
+++ b/stack/src/stack.ads
@@ -0,0 +1,26 @@
1generic
2 type T is private;
3package Stack is
4 type Stack is private;
5
6 -- Push a value into the stack.
7 procedure Push (S : in out Stack; Val : T);
8
9 -- Pop a value from the stack.
10 function Pop (S : in out Stack; Val : out T) return Boolean;
11
12 -- Return true if the stack is empty, false otherwise.
13 function Empty (S : Stack) return Boolean;
14private
15 type Node;
16 type Node_Access is access Node;
17
18 type Node is record
19 Val : T;
20 Bottom : Node_Access;
21 end record;
22
23 type Stack is record
24 Top : Node_Access;
25 end record;
26end Stack;