Ada 如何使用递归删除元素?

Ada 如何使用递归删除元素?,ada,Ada,在这段代码中,我构建了一个包含三个整数(5、10、15)的列表,我需要的帮助是,我需要询问用户他/她想要删除哪些元素,然后只返回剩下的元素。我需要为此编写一个子程序,仅通过使用递归,我需要删除用户不需要的元素 主程序: with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Linked_List; use Linked_List; procedure Main_Rem

在这段代码中,我构建了一个包含三个整数(5、10、15)的列表,我需要的帮助是,我需要询问用户他/她想要删除哪些元素,然后只返回剩下的元素。我需要为此编写一个子程序,仅通过使用递归,我需要删除用户不需要的元素

主程序:

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Linked_List; use Linked_List;

procedure Main_Remove is
I : Integer;
L : List_Type;
begin
Build_Test_List(L); -- builds a list of 3 integers (5 => 10 => 15)
Put(L);
Put("Which elements do you want to remove/delete ");
Get(I);
Remove(L, I);
Put(L);
end Main_Remove;
包装:

package Linked_List is
type List_Type is private;
procedure Put(Item : in List_Type);
procedure Build_Test_List(Item :    out List_Type;
             Base : in     Integer := 5);
private
type E_Type;
type List_Type is access E_Type;
type E_Type is
record
Data : Integer;
Next : List_Type;
end record;
end Linked_List;
包装机构:

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

package body Linked_List is

procedure Put(Item : in List_Type) is
  P : List_Type := Item;
begin
Put("Listan: ");
while P /= null loop
if P /= Item then
Put(" -> ");
end if;
Put(P.Data, Width => 0);
P := P.Next;
end loop;      
New_Line;
end Put;
procedure Insert_First(L : in out List_Type;
          D : in     Integer) is
begin
L := new E_Type'(Data => D, Next => L);
end Insert_First;

procedure Build_Test_List(Item :    out List_Type;
             Base : in     Integer := 5) is
begin
  for I in reverse 1..3 loop
 Insert_First(Item, Base * I);
  end loop;
end Build_Test_List;  
end Linked_List;

这样做就可以了,但有保留:特别是内存泄漏

procedure Remove (L : in out List_Type; Item : Integer) is
begin
当列表为空时,必须停止递归

  if L = null then
     return;
  end if;
列表不是空的。接下来要做什么取决于当前列表元素是否包含我们要查找的值

  if L.Data = Item then
此项目需要从列表中删除。通过更改原始指针(来自列表头或上一个元素)跳过此元素,然后处理该元素来完成此操作。
这是内存泄漏发生的点。显然,需要释放初始的
L
指向的单元格,但必须注意操作顺序

     L := L.Next;
     Remove (L, Item);
  else
项目保留在列表中,继续下一个元素

     Remove (L.Next, Item);
  end if;
end Remove;

这样做就可以了,但有保留:特别是内存泄漏

procedure Remove (L : in out List_Type; Item : Integer) is
begin
当列表为空时,必须停止递归

  if L = null then
     return;
  end if;
列表不是空的。接下来要做什么取决于当前列表元素是否包含我们要查找的值

  if L.Data = Item then
此项目需要从列表中删除。通过更改原始指针(来自列表头或上一个元素)跳过此元素,然后处理该元素来完成此操作。
这是内存泄漏发生的点。显然,需要释放初始的
L
指向的单元格,但必须注意操作顺序

     L := L.Next;
     Remove (L, Item);
  else
项目保留在列表中,继续下一个元素

     Remove (L.Next, Item);
  end if;
end Remove;

你以前学过任何语言的链表吗?Ada是我的第一种编程语言。如果你能把你的代码排列整齐,那将非常有帮助。在风格方面,
Insert\u First
应该在软件包规范中,而
Build\u Test\u List
应该在主程序中(如果它甚至值得成为一个过程的话)。你以前用过任何语言学习过链表吗?Ada是我的第一种编程语言。如果你能把代码排列整齐,那将非常有帮助。在风格方面,
Insert\u First
应该在包规范中,而
Build\u Test\u List
应该在主程序中(如果它甚至值得成为一个过程的话)。