gpt4 book ai didi

pointers - Fortran 如何释放链表?

转载 作者:行者123 更新时间:2023-12-02 19:22:20 26 4
gpt4 key购买 nike

我想在 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

关于pointers - Fortran 如何释放链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9184675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com