没有链表的解决方案。
这里假设向量“r”包含双精度值。
请注意,此解决方案不使用指针,只使用可分配数组,这样可以保证避免内存泄漏。重新分配的数量是有限的(log2(list%n)),但是可以接受分配 list%result 的大小大于实际需要的大小(最多两次)。
最后,向量“r”在列表中重复了(在python版本中不是这种情况)。
module extendable_list
implicit none
type result_type
double precision,allocatable :: vector(:)
end type
type list_type
integer :: n
type(result_type),allocatable :: result(:)
end type
contains
subroutine append(list,r)
type(list_type),intent(inout) :: list
double precision,intent(in) :: r(:)
type(result_type),allocatable :: temporary(:)
integer :: i
if(.not.allocated(list%result)) then
allocate(list%result(10))
list%n=0
else if(list%n >= size(list%result)) then
allocate(temporary(2*list%n))
do i=1,list%n
call move_alloc(list%result(i)%vector,temporary(i)%vector)
enddo
call move_alloc(temporary,list%result)
endif
list%n=list%n+1
allocate(list%result(list%n)%vector(size(r)))
list%result(list%n)%vector=r
end subroutine
end module
program main
use extendable_list
implicit none
type(list_type) :: list
integer :: i
do i=1,10
call append(list,(/1.d0,3.d0/))
call append(list,(/7.d0,-9.d0,45.d0/))
enddo
do i=1,list%n
write(*,*) list%result(i)%vector
enddo
end program
结果:
coul@b10p5001:~/test$ ifort t65.f90
coul@b10p5001:~/test$ ./a.out
1.00000000000000 3.00000000000000
7.00000000000000 -9.00000000000000 45.0000000000000
1.00000000000000 3.00000000000000
7.00000000000000 -9.00000000000000 45.0000000000000
1.00000000000000 3.00000000000000
7.00000000000000 -9.00000000000000 45.0000000000000
1.00000000000000 3.00000000000000
7.00000000000000 -9.00000000000000 45.0000000000000
1.00000000000000 3.00000000000000
7.00000000000000 -9.00000000000000 45.0000000000000
1.00000000000000 3.00000000000000
7.00000000000000 -9.00000000000000 45.0000000000000
1.00000000000000 3.00000000000000
7.00000000000000 -9.00000000000000 45.0000000000000
1.00000000000000 3.00000000000000
7.00000000000000 -9.00000000000000 45.0000000000000
1.00000000000000 3.00000000000000
7.00000000000000 -9.00000000000000 45.0000000000000
1.00000000000000 3.00000000000000
7.00000000000000 -9.00000000000000 45.0000000000000