首页 > 解决方案 > 在派生类型过程中区分头节点和其他节点

问题描述

我正在开发一个看起来像这样的模块:

module linked_elems

type link
  integer :: i
  double precision :: a
  type(link), pointer :: parent=>null()
  type(link), pointer :: child=>null()
contains
  procedure forward_op
  ! and all the usual linked list stuff
end type

type(link), target :: head

contains

subroutine forward_op(ln)

class(link), target :: ln

! do stuff to ln%i and ln%a

! if ln == head do extra stuff to ln%i and ln%a

!Operands of comparison operator '==' at (1) are CLASS(link)/TYPE(link)V
!if (ln == head) then  
!  print *,'ln is head'
!endif

!Error: ‘pointer’ argument of ‘associated’ intrinsic at (1) must be a POINTER
!if (associated(ln, head)) then  
!  print *, 'ln is head'
!endif

end subroutine

end module

真正的模块涉及更多,但这说明了我遇到的问题。在subroutine forward_op()中,链表的头节点需要与其他任何节点略有不同。我无法弄清楚子例程如何判断它是否正在处理头节点。在我尝试过的两种方法的代码中,以及它们给出的编译错误。

我可以通过以下事实来区分头节点:如果代码执行正确,它将是唯一一个其父元素未关联的节点。但是也许稍后有人会出现并尝试将要使用的代码放入例如需要循环链表的方式中,然后父标准将不起作用。无论如何,在我看来,除了其任何元素的值之外,仅根据其自身在内存中的存在来找到某种方法来检测头节点似乎更可取。有没有办法做到这一点?

标签: linked-listfortran

解决方案


推荐阅读