我是Ada的新手,我正在做链表计划并面临一些奇怪的问题 当我在列表中添加节点时,我可以遍历到最后一个节点并打印节点值, 但是当我遍历实际打印值程序退出时,下面是我的代码,
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;
由于
答案 0 :(得分:2)
您永远不会真正添加节点。 所有这一切都造成了内存泄漏:
Temp_Node := new Node'(Id,Value,null);
我认为你的意思是:
Temp_Node.Next := new Node'(Id,Value,null);
答案 1 :(得分:0)
使用递归更容易或更优雅
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(Node: in Node_Ptr) is
begin
if Node /= null then
Integer_Text_IO.Put(Node.Id);
Integer_Text_IO.Put(Node.Value);
Ada.Text_IO.New_Line;
Print_List(Node.Next);
end if;
end Print_List;
procedure Append_Node(Id: Integer; Value: Integer; New_Node: in out Node_Ptr) is
begin
if New_Node = null then
New_Node := new Node'(Id,Value,null);
Ada.Text_IO.Put("Adding Head node");
Ada.Text_IO.New_Line;
else
if New_Node.Next /= null then
Append_Node(Id, Value, New_Node.Next);
else
Ada.Text_IO.Put("Adding Next node");
Ada.Text_IO.New_Line;
New_Node.Next := new Node'(Id, Value, null);
end if;
end if;
end Append_Node;
Head : Node_Ptr := null;
begin
Append_Node(1, 1, Head);
Append_Node(2, 2, Head);
Append_Node(3, 3, Head);
Append_Node(4, 4, Head);
Append_Node(5, 5, Head);
Print_List(Head);
Append_Node(6, 6, Head);
Print_List(Head);
end Ada_Link_List;