with Ada.Text_IO; use Ada.Text_IO;
with Ada.Unchecked_Deallocation;

package body Lists is
   procedure Free is new Ada.Unchecked_Deallocation (Node, List);

   procedure Push (L : in out List; V : Integer) is
   begin
      L := new Node'(Value => V, Next => L);
   end Push;

   procedure Append (L : in out List; V : Integer) is
   begin
      if L = null then
         L := new Node'(Value => V, Next => null);
      else
         Append (L.Next, V);
      end if;
   end Append;

   procedure Reverse_List (L : in out List) is
      R : List := null;
   begin
      while L /= null loop
         declare
            N : List := L.Next;
         begin
            L.Next := R;
            R := L;
            L := N;
         end;
      end loop;
      L := R;
   end Reverse_List;

   --  the traversals below are loops: an observer reads the list, a borrower changes it in
   --  place, and Clear frees it node by node

   procedure Length (L : List; N : out Natural) is
      X : access constant Node := L;
   begin
      N := 0;
      while X /= null loop
         if N < Natural'Last then
            N := N + 1;
         end if;
         X := X.Next;
      end loop;
   end Length;

   procedure Print (L : List) is
      X : access constant Node := L;
   begin
      while X /= null loop
         Put (Integer'Image (X.Value));
         X := X.Next;
      end loop;
      New_Line;
   end Print;

   procedure Halve_All (L : in out List) is
      B : access Node := L;
   begin
      while B /= null loop
         B.Value := B.Value / 2;
         B := B.Next;
      end loop;
   end Halve_All;

   procedure Clear (L : in out List) is
   begin
      while L /= null loop
         declare
            Rest : List := L.Next;
         begin
            Free (L);
            L := Rest;
         end;
      end loop;
   end Clear;
end Lists;
