You must delete all node manually. This is where the "Object Oriented" style is useful.
module LinkedListModule implicit none private public :: LinkedListType public :: New, Delete public :: Append interface New module procedure NewImpl end interface interface Delete module procedure DeleteImpl end interface interface Append module procedure AppendImpl end interface type LinkedListType type(LinkedListEntryType), pointer :: first => null() end type type LinkedListEntryType integer :: data type(LinkedListEntryType), pointer :: next => null() end type contains subroutine NewImpl(self) type(LinkedListType), intent(out) :: self nullify(self%first) end subroutine subroutine DeleteImpl(self) type(LinkedListType), intent(inout) :: self if (.not. associated(self%first)) return current => self%first next => current%next do deallocate(current) if (.not. associated(next)) exit current => next next => current%next enddo end subroutine subroutine AppendImpl(self, value) if (.not. associated(self%first)) then allocate(self%first) nullify(self%first%next) self%first%value = value return endif current => self%first do if (associated(current%next)) then current => current%next else allocate(current%next) current => current%next nullify(current%next) current%value = value exit endif enddo end subroutine end module
Beware: it's past midnight, and I don't really like coding in the browser window. This code may not work. This is just a layout.
Use it as
program foo use LinkedListModule type(LinkedListType) :: list call New(list) call Append(list, 3) call Delete(list) end program
Stefano borini
source share