我编写了一种算法,用于将按课程对象的number
成员变量排序的课程对象插入链表。效果很好,除非我尝试插入重复项,例如两个2420实例。列表__str__
输出当前看起来像这样:
cs1400 Introduction to Programming Grade:3.6 Credit Hours: 4
cs1410 C++ Programming Grade:2.6 Credit Hours: 4
cs2420 Introduction to Data Structures Grade:3.2 Credit Hours: 4
cs2810 Computer Architecture Grade:3.8 Credit Hours: 3
这是我的insert方法代码
def insert(self, course=None):
"""Insert the specified Course in Course Number ascending order."""
def insert_helper(cursor, course):
if course is None:
return
if course.number <= self.head.number: # start of the list
self.head = course
return
if cursor.next is None or course.number <= cursor.next.number: #
course.next = cursor.next
cursor.next = course
return
insert_helper(cursor.next, course)
if self.head is None:
self.head = course
return
cursor = self.head
insert_helper(cursor, course)
诀窍使我全神贯注于递归框架。我希望很快能解决这个问题。
我不认为重复的课程编号本身就是问题。
这里程序有错误:
if course.number <= self.head.number: # start of the list
self.head = course
return
如果执行此代码段的最后两行,您的列表将成为包含course
且不包含其他内容的单例列表。
将其与下一个if
语句进行比较,如果条件为真,则执行
course.next = cursor.next
您需要将course.next
都设置为两个位置。
[还要注意,如果在第一次调用course.number <= self.head.number
期间insert_helper
不为真,则在任何递归调用中也都不为真。在首次调用该函数之前,最好处理这种情况。