You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python链表中间插入元素时触发TypeError错误求助

链表中间插入元素报错排查:TypeError: '>' not supported between int and NoneType

问题场景与报错信息

我用Python 3在VS Code中实现链表数据结构,尝试向链表中间插入元素时触发错误,报错内容如下:

File "d:\coding\python_in_hole\data structure\tempCodeRunnerFile.py", line 69, in 
root.insert_at(2, 31) File "d:\coding\python_in_hole\data structure\tempCodeRunnerFile.py", line 45, in insert_at
if index < 0 or index > self.get_length():
TypeError: '>' not supported between instances of 'int' and 'NoneType'

完整实现代码:

class Node:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next


class linked_list:
    def __init__(self):
        self.head = None

    def insert_at_begining(self, data):
        node = Node(data, self.head)
        self.head = node

    def print(self):
        itr = self.head
        llstr = ''
        while itr:
            suffix = ''
            if itr.next:
                suffix = '-->'
            llstr += str(itr.data) + suffix
            itr = itr.next
        print(llstr)

    def get_length(self):
        count = 0
        itr = self.head
        while itr:
            count = count+1
            itr = itr.next
        print(count)
    
    def insert_at_end(self, data):
        if self.head is None:
            self.head = Node(data, None)
            return
        
        itr = self.head
        while itr.next:
            itr = itr.next
        itr.next = Node(data, None)

    def insert_at(self, index, data):
        if index < 0 or index > self.get_length():
            raise Exception("Invalid Index")
        
        if index == 0:
            self.insert_at_begining(data)
            return

        itr = self.head
        count = 0
        while itr:
            if count == index-1:
                node = Node(data, itr.next)
                itr.next = node
                break
            
            itr = itr.next
            count += 1

if __name__ == '__main__':
    root = linked_list() 
    root.insert_at_begining(5)
    root.insert_at_begining(15)
    root.insert_at_begining(10)
    root.insert_at_end(34)
    root.insert_at(2, 31)
    root.insert_at_end(45)
    root.print()
    root.get_length()

问题原因与修复方案

核心问题

get_length方法仅打印链表长度,未返回任何值(Python中无return语句的函数默认返回None)。当insert_at方法执行index > self.get_length()时,实际是在拿整数和None做比较,直接触发类型错误。

修复步骤

  1. 修改get_length方法,将print(count)替换为return count,让方法返回整数类型的链表长度:
def get_length(self):
    count = 0
    itr = self.head
    while itr:
        count += 1
        itr = itr.next
    return count
  1. 若需要打印链表长度,在主函数中将root.get_length()改为print(root.get_length()),把打印逻辑从方法内剥离到外部。

修复后效果

代码可正常执行插入操作,最终链表输出为:10-->15-->31-->5-->34-->45,链表长度为6。

内容的提问来源于stack exchange,提问作者believe itsreal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 16:40:53