pointers - Fortran 如何释放链表?

标签 pointers memory-management linked-list 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

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

相关文章:

c - 需要帮助理解我的示例的 malloc(0)

iphone - 在 ViewController ("Page swipe Style ScrollView"中收到内存警告)

c - 在堆栈上创建 char** 缓冲区的更好方法?

java - 交换两个链表条目

c - 我对链表有一些问题

c++ - 创建指针时没有调用构造函数吗?

c - int*a 和 char *a 的区别?

c - 使用/比较内存地址的类型

c - 为什么这个链表从上次输入打印出来? C链表程序

C 动态结构(malloc 和 free)