How does Fortran release linked lists?

I would like to use linked lists in Fortran to store an array of data of length undefined.

I have the following setup:

TYPE linked_list INTEGER :: data TYPE(linked_list) :: next_item => NULL() END TYPE 

Now let's say that I create a list like this:

 TYPE(LINKED_LIST) :: example_list example_list%data =1 ALLOCATE(example_list%next_item) example_list%next_item%data = 2 ALLOCATE(example_list%next_item%next_item) example_list%next_item%next_item%data = 3 

My question is: if I do:

 DEALLOCATE(example_list) 

will all levels of nested levels also be freed, or will I need to go through the list to the deepest element and free myself from the deepest element up?

+7
source share
1 answer

You must delete all node manually. This is where the "Object Oriented" style is useful.

 module LinkedListModule implicit none private public :: LinkedListType public :: New, Delete public :: Append interface New module procedure NewImpl end interface interface Delete module procedure DeleteImpl end interface interface Append module procedure AppendImpl end interface type LinkedListType type(LinkedListEntryType), pointer :: first => null() end type type LinkedListEntryType integer :: data type(LinkedListEntryType), pointer :: next => null() end type contains subroutine NewImpl(self) type(LinkedListType), intent(out) :: self nullify(self%first) end subroutine subroutine DeleteImpl(self) type(LinkedListType), intent(inout) :: self if (.not. associated(self%first)) return current => self%first next => current%next do deallocate(current) if (.not. associated(next)) exit current => next next => current%next enddo end subroutine subroutine AppendImpl(self, value) if (.not. associated(self%first)) then allocate(self%first) nullify(self%first%next) self%first%value = value return endif current => self%first do if (associated(current%next)) then current => current%next else allocate(current%next) current => current%next nullify(current%next) current%value = value exit endif enddo end subroutine end module 

Beware: it's past midnight, and I don't really like coding in the browser window. This code may not work. This is just a layout.

Use it as

 program foo use LinkedListModule type(LinkedListType) :: list call New(list) call Append(list, 3) call Delete(list) end program 
+9
source

All Articles