我已经实现了一个用 Fortran 编写的通用链表 (genII.f90),可在 http://fortranwiki.org/fortran/show/Linked+list中找到 。
我对其进行了测试,一切正常,除了 LI_Remove_Head 函数似乎没有释放内存。
我将函数 LI_Destruct(见下文)添加到原始模块中,结果相同,它不会释放内存。
SUBROUTINE LI_Destruct(List)
implicit none
TYPE(List_Type),INTENT(INOUT),TARGET :: List
TYPE(Link_Ptr_Type) :: Link_current, Link_next
Link_next%P =>List%Head%next
do while (associated(Link_next%P))
Link_current%P => Link_next%P
Link_next%P => Link_next%P%next
deallocate(Link_current%P)
end do
end subroutine LI_destruct
我当然错过了一些东西,所以我的问题有两个:1-代码中是否有错误?为什么内存没有被“deallocate”清空?
2-fortran 是否存在更好且几乎标准的通用链表?
我添加了下面用于进行测试的简单代码:
PROGRAM test_list
! Defines data and other list(s) and arrays for particles.
USE Generic_List, ONLY : Link_Ptr_Type,Link_Type,List_Type
USE Generic_List, ONLY : LI_Init_List,LI_Add_To_Head,LI_Add_To_Tail,LI_Get_Head,&
LI_Remove_Head,LI_Get_Next,LI_Associated,LI_Get_Len, LI_destruct
IMPLICIT NONE
TYPE:: Particle_data
REAL, dimension(2) :: pos !! Coordinate dimensionali
END TYPE Particle_data
! Definition of the types necessary for the list
TYPE Particle_Node
TYPE(Link_Type) :: Link
TYPE(Particle_data), pointer :: Data
END TYPE Particle_Node
TYPE Particle_Node_ptr
TYPE(Particle_Node), pointer :: P
END TYPE Particle_Node_ptr
! Create array of lists in order to allow classify the particles
TYPE(List_Type), allocatable :: ao_Particle_List(:)
TYPE(Link_Ptr_Type) :: Link
TYPE(Particle_Node_ptr) :: Particle_elem
!-------------------------------------------------------------!
!-------------------------------------------------------------!
INTEGER, parameter :: Npart_test = 1000000 ! , nPart
INTEGER :: i,iter,j,item,nBuffer
REAL :: pos(2)
nBuffer = 5
IF (ALLOCATED(ao_Particle_List)) DEALLOCATE(ao_Particle_List)
ALLOCATE(ao_Particle_List(0:nBuffer))
! Init list used for temporary construction
DO iter=0,nBuffer
CALL LI_Init_List(ao_Particle_List(iter))
ENDDO
DO j=1,NBuffer
DO i=1,Npart_test
pos(1)=i*1.0; pos(2)=j*i
ALLOCATE(Particle_elem%P); ALLOCATE(Particle_elem%P%Data) ! Allocate data before store
Particle_elem%P%Data%pos = pos
! Elem is treated and should be put at head of the list ao_Particle_List(item)
item=j
Link = TRANSFER(Particle_elem,Link); CALL LI_Add_To_Head(Link,ao_Particle_List(item)) ! STORAGE
END DO
END DO
WRITE(*,*) "List is full, see RAM"; READ(*,*)
! Write(*,*) "Destruct list"
DO iter=0,nBuffer
CALL LI_Destruct(ao_Particle_List(iter))
ENDDO
IF (ALLOCATED(ao_Particle_List)) DEALLOCATE(ao_Particle_List)
WRITE(*,*) "List is empty, see RAM"; READ(*,*)
END PROGRAM
谢谢大家,约翰