Pointer components may ``point to'' objects of any intrinsic type, any derived type previously defined or to the type being currently defined. Note that it is not possible to have a target type which has yet to be defined.
It is therefore possible to construct linked lists using derived types and pointer components. For example, objects of the type Node contain a value, an id number, a pointer to the previous node and one to the next node in the double linked list.
module CircularList
implicit none
type node
integer :: id
real :: value
type(node), pointer :: prev, next
end type node
!
contains
!
function BuildCircularList(n)
implicit none
integer, intent(in) :: n
type(node), pointer :: BuildCircularList
integer :: i, ierr
type(node), pointer :: head, temp, curr
!
allocate(temp,stat=ierr)
if (ierr.ne.0) then
print*, "allocation error"; return
end if
head%id = 1; head%value = 0.0
!
curr => head
do i=2,n
allocate(temp,stat=ierr)
if (ierr.ne.0) then
print*, "allocation error"; return
end if
temp%id = i; temp%value = 0.0
curr%next => temp; temp%prev => curr; curr => temp
end do
! the next 2 lines circularly ``close'' the list
curr%next => head; head%prev => curr
BuildCircularList => head
end function BuildCircularList
!
end module CircularList
program test
use CircularList
implicit none
type(node), pointer :: f, b
f => BuildCircularList(3)
b => f
do i=1,7
print*, f%id, f%value, b%id, b%value
f => f%next; b => b%prev
end do
end program test