Skip to content
Fortran

Derived Types and Pointers

Custom types with allocatable components and pointers.

By EZ4Code Team
derived-typepointerlinked-list

Code

module linked_list
  implicit none

  type :: node
    integer :: value
    type(node), pointer :: next => null()
  end type

  type :: list_type
    type(node), pointer :: head => null()
    integer :: count = 0
  contains
    procedure :: push
    procedure :: print => print_list
    final :: free_list
  end type

contains

  subroutine push(self, val)
    class(list_type), intent(inout) :: self
    integer, intent(in) :: val
    type(node), pointer :: new_node
    allocate(new_node)
    new_node%value = val
    new_node%next => self%head
    self%head => new_node
    self%count = self%count + 1
  end subroutine

  subroutine print_list(self)
    class(list_type), intent(in) :: self
    type(node), pointer :: cur
    cur => self%head
    do while (associated(cur))
      print *, cur%value
      cur => cur%next
    end do
  end subroutine

  subroutine free_list(self)
    type(list_type), intent(inout) :: self
    type(node), pointer :: cur, tmp
    cur => self%head
    do while (associated(cur))
      tmp => cur%next
      deallocate(cur)
      cur => tmp
    end do
  end subroutine
end module

Explanation

Fortran pointers are aliases (not like C pointers) — use => to point, associated() to check. final procedures run on destruction (like C++ destructors). allocatable is preferred over pointer for automatic memory management — pointer requires manual deallocate. Use pointer for linked structures (graphs, trees).

More Fortran Snippets