您必須手動釋放每個節點。這就是風格「面向對象」有用的地方。
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
它一直以來我用Fortran這樣做很長一段時間,但我敢肯定,你必須手動解除分配。如果你只是解除頭部分配,那麼你將失去參考併發生內存泄漏。 – ChrisF 2012-02-07 22:04:46
是的。我對此非常害怕。但是我必須說,我遇到了麻煩,那是什麼意思,滾動我自己的垃圾回收? – EMiller 2012-02-07 22:09:14
您無法實施內存管理的fortran。 – 2012-02-07 22:57:36