Fortran递归选择排序可分配单向链表实现问题求助
可分配递归单向链表的选择排序实现问题
任务要求:实现可分配递归单向链表的选择排序,按姓氏字母顺序排序,排序步骤为:
- 找到链表中姓氏最小的节点;
- 将该节点从原位置移除并填补空缺(例如将
A -> minimum -> B -> C变为A -> B -> C); - 将该节点放到链表头部(例如变为
minimum -> A -> B -> C)。
目前遇到的问题:已编写代码,但无法正确将最小节点移到链表头部。尝试的节点移动方法仅能处理单个元素,无法保留后续链表关联。已耗时40多小时调试仍无进展,虽认为RemoveNode子程序正确,但也不排除问题出在此处。
代码片段
ChooseAndPaste子程序
22 recursive subroutine ChooseAndPaste(unsorted, minimum, current) 23 type(SourceLine), allocatable :: unsorted 24 type(SourceLine), allocatable :: minimum 25 type(SourceLine), allocatable :: current 26 type(SourceLine), allocatable :: temp 27 if (allocated(current)) then 28 print *, "makr 3 ", current%field 29 if (current%field < minimum%field) then 30 call ChooseAndPaste(unsorted, current, current%next) 31 else 32 call ChooseAndPaste(unsorted, minimum, current%next) 33 end if 34 else 35 if ((allocated(unsorted) .and. allocated(minimum) .and. (unsorted%field /= minimum%field))) then 36 print *, minimum%field 37 call RemoveNode(unsorted, minimum) 38 ! call move_alloc(unsorted, temp) 39 ! call move_alloc(minimum, unsorted) 40 ! call move_alloc(temp, unsorted%next) 41 end if 42 end if 43 end subroutine ChooseAndPaste
注释38-40行时,结果接近有序,但无法将最小节点添加到链表头部。38-40行的方法仅移动顶层元素,无法保留后续关联。
SelectionSort上层调用子程序
recursive subroutine SelectionSort(unsorted) 11 type(SourceLine), allocatable :: unsorted 12 13 if (allocated(unsorted)) then 14 call ChooseAndPaste(unsorted, unsorted, unsorted%next) 15 16 if (.not. allocated(unsorted)) return ! <-- this line was added because of this issue 17 call SelectionSort(unsorted%next) 18 end if 19 20 end subroutine SelectionSort
数据结构定义
type SourceLine character(:, CH_), allocatable :: field type(SourceLine), allocatable :: Next end type SourceLine
RemoveNode子程序
46 recursive subroutine RemoveNode(unsorted, minimum) 47 type(SourceLine), allocatable :: unsorted 48 type(SourceLine), allocatable :: minimum 49 type(SourceLine), allocatable :: Temp 50 51 52 if (.not. allocated(unsorted)) return 53 54 ! Check if current node is the target 55 if (unsorted%field == minimum%field) then 56 if (allocated(unsorted%next)) then 57 ! Keep the rest of the list 58 call move_alloc(unsorted%next, Temp) 59 call move_alloc(Temp, unsorted) 60 else 61 ! This was the last node 62 deallocate(unsorted) 63 print *, "mark 1" 64 end if 65 return 66 end if 67 ! Recursively check next nodes 68 if (allocated(unsorted%next)) then 69 call RemoveNode(unsorted%next, minimum) 70 end if 71 end subroutine RemoveNode
个人判断:认为RemoveNode子程序正确,但也不排除存在问题的可能。
内容的提问来源于stack exchange,提问作者NikPlayAnon
相关产品推荐
相关产品推荐

