Consider the following example of a linked list.
program pllassign
implicit none
type ll
integer :: i=-1
type(ll), pointer :: next=>null()
end type ll
type(ll), target, save :: first, second, third
type(ll), pointer :: current => first
third = ll(3,null())
second = ll(2,third)
first = ll(1,second)
do while (associated(current))
write(*,*) 'current%i=', current%i
current => current%next
enddo
end program pllassign
This works as intended, with output like:
$ gfortran pllassign.f90 && a.out
current%i= 1
current%i= 2
current%i= 3
It occurred to me that it might be nice if the linked list could be constructed with initialization rather than assignment. So I tried this:
program pllinit
implicit none
type ll
integer :: i=-1
type(ll), pointer :: next=>null()
end type ll
type(ll), target, save :: third = ll(3,null())
type(ll), target, save :: second = ll(2,third)
type(ll), target, save :: first = ll(1,second)
type(ll), pointer :: current => first
do while (associated(current))
write(*,*) 'current%i=', current%i
current => current%next
enddo
end program pllinit
This does not compile, with either gfortran or NAG, so I figure I must be doing something wrong. Is it possible to construct a linked list using pointers with initialization?
NOTE: Of course, in fortran, one would not use pointer
elements of the ll
derived type, one would naturally use allocatable
instead. However, I already know that it is not allowed to initialize an allocatable
variable, so I’m using pointer
instead in these examples just because of that language limitation.
EDIT: I changed the original DO loop to a simpler DO WHILE loop.