MODULE ListModule TYPE ListElem REAL :: value; TYPE(ListElem), POINTER :: next; END TYPE ListElem END MODULE |
Example:
TYPE(ListElem), POINTER :: head NULLIFY(head) ! head = NULL |
Example:
TYPE(ListElem), POINTER :: head
...
if ( .NOT. ASSOCIATED( head ) THEN ! if ( head != NULL )
...
else
...
end if
|
|
MODULE ListModule TYPE ListElem REAL :: value; TYPE(ListElem), POINTER :: next; END TYPE ListElem END MODULE |
TYPE(ListElem), POINTER :: p ALLOCATE(p) !! C++: "p = new ListElem();" |
TYPE(ListElem), POINTER :: head TYPE(ListElem), POINTER :: elem NULLIFY(head) ! head = NULL |
Result:
|
ALLOCATE( elem ) elem%value = 1500 |
Result:
|
elem%next => head // Make new list element points
// to the start of "old list"
head => elem // Make "head" points to
// the **new** starting object
|
Result:
|
|
|
FUNCTION InsertList(head, elem)
USE ListModule
IMPLICIT NONE
type( ListElem ), pointer :: head, elem
type( ListElem ), pointer :: InsertList
elem%next => head
InsertList => elem
END FUNCTION
|
|
|
FUNCTION DeleteList(head)
USE ListModule
IMPLICIT NONE
type( ListElem ), pointer :: head
type( ListElem ), pointer :: DeleteList
type( ListElem ), pointer :: h
IF ( associated( head ) ) THEN
h = head ! Use to deallocate
head => head%next ! 2nd elem is now head
deallocate(h) ! Deallocate old first elem
END IF
DeleteList => head
END FUNCTION
|
PROGRAM LinkedList
USE ListModule
INTERFACE
SUBROUTINE PrintList(head)
USE ListModule
type( ListElem ), pointer :: head
END SUBROUTINE
FUNCTION InsertList(head, elem)
USE ListModule
type( ListElem ), pointer :: head, elem
type( ListElem ), pointer :: InsertList
END FUNCTION
FUNCTION DeleteList(head)
USE ListModule
type( ListElem ), pointer :: head
type( ListElem ), pointer :: DeleteList
END FUNCTION
END INTERFACE
! ---------------------------------------------
! Start of main program
! ---------------------------------------------
type( ListElem ), pointer :: head
type( ListElem ), pointer :: newElem
integer, parameter :: N = 4
NULLIFY( head ) ! Empty list
! ---------------------------------------------
! Add the N elements
! ---------------------------------------------
DO i = 1, N
ALLOCATE( newElem )
CALL random_number( newElem%f )
head => InsertList(head, newElem)
CALL PrintList(head)
END DO
head => DeleteList(head)
END PROGRAM LinkedList
|
PS: Nothing has changed in the theory. You should be able to figure out inserting at different places yourself...