Re: traverse linked list (Fortran 90)
- From: "Kurt Kallblad" <kurt.kallblad@xxxxxxxx>
- Date: Wed, 17 Sep 2008 12:49:01 +0200
"e p chandler" <epc8@xxxxxxxx> wrote in message news:a8992137-a201-45db-a350-32d53fe96916@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
See http://www.pcc.qub.ac.uk/tec/courses/f77tof90/stu-notes/f90studentMIF_6.html
for code which creates, traverses and destroys a linked list. Note
that this is a stack - last in - first out.
I found the code a bit quirky and decided to write my own so that the
list would be traversed in the order in which items were entered. So I
sat down and wrote out the following on a legal pad. It compiled and
ran on the first try!
program linked_list
implicit none
type node
integer :: i
type(node), pointer :: p
end type node
type(node), pointer :: h, t, c
integer :: i
nullify(h)
do
read *, i
if ( i == 0 ) exit
allocate(c)
c%i = i
nullify(c%p)
if ( .not. associated(h) ) then
h => c
else
t%p => c
end if
t => c
end do
do
c => h
if ( .not. associated(c) ) then
exit
else
print *, c%i
h => c%p
deallocate(c)
end if
end do
end program linked_list
I acutally understand what this code does! The only subtle part is
t%p => c
--- If the list is NOT empty, add the newly created node onto the
chain.
-- e
My knowlege in English isn't the best but I guess "The only subtle part" indicates a question.
As you create a first in - first out list each new node must be pointed to by the preceding node. This is achived by use of the pointer t.
At the end of the first loop are t and c pointing at the same newly allocated memory. After next allocation c will point at another location but t still point at the preceeding location. Thus t%p => c will give the needed link from the preceeding node t to the new node c when the list is not empty.
With an empty list, the pointer h is used to save the location of the first created node.
A small tips:
In Fortran 95 or later you can use the NULL function in the declaration
type(node), pointer :: p => null()
and skip
nullify(h) and nullify(c%p)
Hope this is to some help,
Kurt
.
- References:
- traverse linked list (Fortran 90)
- From: e p chandler
- traverse linked list (Fortran 90)
- Prev by Date: Re: Reading external variables from a library (BIND)
- Next by Date: Re: pointer components and memory leaks
- Previous by thread: Re: traverse linked list (Fortran 90)
- Next by thread: Re: traverse linked list (Fortran 90)
- Index(es):
Relevant Pages
|