Linked List of Strings
MC logo
 

Linked List of Strings

Ada Code Examples


<<Integer Stack with Exceptions Client Download General Stack Package>>
--
-- Simple linked list.  This reads in strings using a paramertised type
-- to avoid a second allocation of the string.
--

-- This requests the generic method method to explicitly free storage.
with Ada.Text_IO;
use Ada.Text_IO;
with Ada.Unchecked_Deallocation;
use Ada;

procedure ll3 is
   type Node;                           -- Node type.
   type Node_Ptr is access Node;        -- Node_Ptr points to those.

   type Node(L: Integer) is record      -- Now I'll tell you what Node is.
      Data: String(1..L);
      Next: Node_Ptr;
   end record;

   -- This declares the Free procedure as the de-allocator for the
   -- node type.  Free is the traditional name, but we could have
   -- used any procedure name.
   procedure Free is new Unchecked_Deallocation(Node, Node_Ptr);

   Head: Node_Ptr;                      -- Head of the list.
   New_Node: Node_Ptr;                  -- Created node.
   Scan_Ptr: Node_Ptr;                  -- Scan the list.
   In_Str: String(1..100);              -- Input integer.
   Zombie: Node_Ptr;                    -- The node about to die.
   Len: Integer;                        -- Number of characters read.
begin
   -- Read in strings until we reach the end.
   begin
      loop
         -- Read a string.
         Put("> ");
         Get_Line(In_Str, Len);

         -- Create a node for it, filled in.  The initial values on new are
         -- optional, but useful to fill in the new space, much like a
         -- constructor.
         New_Node := new Node'(Len, In_Str(1..Len), null);

         -- Link it into the list.
         New_Node.Next := Head;
         Head := New_Node;
      end loop;
   exception
      when End_Error =>
         New_Line;
   end;

   -- Now print out the integers (backwards.)
   Scan_Ptr := Head;
   loop
      -- If the list is entirely empty, bail out now.
      exit when Scan_Ptr = null;

      -- Print, go to next, and free the node printed.
      Put(Scan_Ptr.Data);
      Zombie := Scan_Ptr;
      Scan_Ptr := Scan_Ptr.Next;
      Free(Zombie);

      -- If there is no next, we are done.
      exit when Scan_Ptr = null;

      -- Since there is a next, print a space to separate the items.
      Put(" ");
   end loop;

   New_Line;
end ll3;
<<Integer Stack with Exceptions Client General Stack Package>>