Fortran如何取消分配链表



我想在Fortran中使用链表来保存未定义长度的数据数组。

我有以下设置:

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

现在假设我创建这样一个列表:

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

我的问题是,如果我执行:

DEALLOCATE(example_list)

所有嵌套级别也会被解除分配吗?还是我需要遍历列表到最深的元素,然后从最深元素向上解除分配?

您必须手动取消分配每个节点。这就是类似"面向对象"的风格的用武之地。

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

小心:现在已经过了午夜,我真的不喜欢在浏览器窗口中编码。此代码可能不起作用。这只是一个布局。

像这样使用

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

最新更新