[插入链表时重复管理

问题描述 投票:0回答:1

我编写了一种算法,用于将按课程对象的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)

诀窍使我全神贯注于递归框架。我希望很快能解决这个问题。

python recursion linked-list singly-linked-list
1个回答
0
投票

我不认为重复的课程编号本身就是问题。

这里程序有错误:

            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不为真,则在任何递归调用中也都不为真。在首次调用该函数之前,最好处理这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.