| 这是chapman书里指针一章的一道作业,大致就是用链表来做插入排序。我实现了一个link list type,这个type 的定义如下 
 [Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode type :: char_node
     character(len=:), pointer :: value
     type(char_node), pointer :: next_value
  end type char_node然后重载了几个计算符(> < ==)
 主程序插入排序的代码如下,
 
 [Fortran] syntaxhighlighter_viewsource syntaxhighlighter_copycode program insertion
  use link_list
  implicit none
  type(char_node), pointer :: head, tail, ptr, ptr1, ptr2
  integer :: istat
  integer :: nvals = 0
  character(len=128) :: temp
  character(len=20) :: filename
  nullify(head,tail,ptr,ptr1,ptr2)
  write (*,*) 'Enter the file name of data to be sorted: '
  read (*,'(a20)') filename
  open (unit=9,file=filename, status = 'old', action = 'read', &
       iostat=istat)
  fileopen: if (istat == 0) then
     input: do
        read (9, *, iostat=istat) temp
        if (istat /= 0) exit input
        nvals = nvals + 1
        allocate(ptr, stat=istat)
        nullify(ptr%value)
        allocate(character(len_trim(adjustl(temp))) :: ptr%value, stat=istat)
        ptr%value = trim(adjustl(temp))
        new : if (.not. associated(head)) then
           head => ptr
           tail => head
           nullify (ptr%next_value)
        else
           front : if(ptr < head) then
              ptr%next_value => head
              head => ptr
           else if (ptr > tail .or. ptr == tail) then
              tail%next_value => ptr
              tail => ptr
              nullify(tail%next_value)
           else
              ! find place to add the value
              ptr1 => head
              ptr2 => ptr1%next_value
              search: do
                 if ((ptr>ptr1 .or. ptr==ptr1) .and. (ptr<ptr2)) then
                    ! insert the value here
                    ptr%next_value => ptr2
                    ptr1%next_value => ptr
                    exit search
                 end if
                 ptr1 => ptr2
                 ptr2 => ptr2%next_value
              end do search
           end if front
        end if new
     end do input
     ptr => head
     output : do
        if (.not. associated(ptr)) exit
        write (*,'(1x,a,i3)') ptr%value, len(ptr%value) 
        ptr => ptr%next_value
     end do output
  else fileopen
     write (*,'(1x,a,i6)') 'File open failed -- status =', istat
  end if fileopen
end program insertion程序能够正常排序,但是每个链表里字符串指针的长度都是128 与 temp字符串相符。为什么我用allocate动态空间的字符串长度还是128?
 谢谢大家。
 
 
 |