Search code examples
adagnat

Link list in Ada


I am new to Ada, I am doing linked list program and facing some strange issue When i am adding node in list i can traverse to last node and print node value, but when i am traversing to actually print values program exits, below is my code,

with 
Ada.Text_IO,
Ada.Integer_Text_IO;
use Ada;

procedure Ada_Link_List is

type Node;
type Node_Ptr is access Node;
type Node is
    record
        Id: Integer;
        Value: Integer;
        Next: Node_Ptr;
    end record;
        procedure Print_List(Firt_Node: in Node_Ptr) is
        Temp_Node : Node_Ptr;
        begin
            if Firt_Node = null then
                Ada.Text_IO.Put("List is Empty");
                Ada.Text_IO.New_Line;
            end if;
            Temp_Node := Firt_Node;
            Ada.Text_IO.Put("List -----");
            while Temp_Node.Next /= null loop
                Ada.Text_IO.Put("while -----");
                Integer_Text_IO.Put(Temp_Node.Id);
                Integer_Text_IO.Put(Temp_Node.Value);
                Temp_Node := Temp_Node.Next;
                Ada.Text_IO.Put("Printing node");
                Ada.Text_IO.New_Line;
            end loop;

        end Print_List;


        procedure Add_Node(Id: Integer; Value: Integer; New_Node: in out Node_Ptr) is
        Temp_Node : Node_Ptr;
        begin
            if New_Node = null then
                New_Node := new Node'(Id,Value,null);
                Ada.Text_IO.Put("Adding Head node");
                Integer_Text_IO.Put(New_Node.Id);
                Ada.Text_IO.New_Line;
            else
                Temp_Node := New_Node;
                while Temp_Node.Next /= null loop
                        Temp_Node := Temp_Node.Next;
                end loop;

                Ada.Text_IO.Put("Adding Next node");
                Ada.Text_IO.New_Line;
                Temp_Node := new Node'(Id,Value,null);
            end if;
        end Add_Node;

    Head_Node : Node_Ptr := null;

    begin
        Add_Node(1,1,Head_Node);
        Add_Node(2,2,Head_Node);
        Add_Node(3,3,Head_Node);
        Add_Node(4,4,Head_Node);
        Add_Node(5,5,Head_Node);
        Print_List(Head_Node);
        Add_Node(6,6,Head_Node);
        Ada.Text_IO.Put("*** Exit ***");

    end Ada_Link_List;

Help me with desired output that i want to print values.

Thanks


Solution

  • You are never really adding nodes. All this does is creating a memory leak:

    Temp_Node := new Node'(Id,Value,null);
    

    I think you mean:

    Temp_Node.Next := new Node'(Id,Value,null);