我想在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)
是否所有嵌套级别都会被释放,或者我是否需要遍历列表到最深的元素并从最深的元素向上释放?
答案 0 :(得分:9)
您必须手动释放每个节点。这就像风格的“面向对象”一样有用。
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