with Ada.Unchecked_Deallocation;
package body Stacks is
   procedure Free is new Ada.Unchecked_Deallocation (Node, Node_Ptr);

   procedure Push (S : in out Stack; X : Integer) is
      N : constant Node_Ptr := new Node'(Value => X, Next => S.Top);
   begin
      S.Top := N;
      S.Count := S.Count + 1;
      S.Repr := Node_Cells.Add (S.Repr, N);
      if Node_Seqs.Length (S.Nodes) > S.Count - 1 then
         S.Nodes := Node_Seqs.Set (S.Nodes, S.Count, N);
      else
         S.Nodes := Node_Seqs.Add (S.Nodes, N);
      end if;
   end Push;

   procedure Pop (S : in out Stack; X : out Integer) is
      Old : Node_Ptr := S.Top;
   begin
      X := Old.Value;
      S.Top := Old.Next;
      S.Repr := Node_Cells.Remove (S.Repr, Old);
      S.Count := S.Count - 1;
      Free (Old);
   end Pop;
end Stacks;
