Python3:AttributeError: ‘NoneType‘ object has no attribute ‘next‘

使用Python实现线性表遇到问题,使用尾插法建立单链表(表中没有元素),就会报错:AttributeError: ‘NoneType’ object has no attribute ‘next’

class linknode():#每个结点有两个数据成员,结点元素和指向下一个结点的指针
    def __init__(self,item):            #创建节点
        self.item = item
        self.next = None
class  linklist():#初始化单链表,头结点指针域为空
    def __init__(self):
        self.head = None

    def is_empty(self):
        return self.head == None

    def listlength(self):
        nod = self.head  # 头结点指针域指向第一个结点
        nodnum = 0
        while (nod != None):
            nodnum += 1
            nod = nod.next  # 下一个结点
        return nodnum
        # 遍历单链表

    def tralist(self):
        show=[]
        nod = self.head
        while nod != None:
            show.append(nod.item)
            nod = nod.next
        return show
    # 头插法建立单链表

    def headcreatlist(self, item):
        nod = linknode(item)  # 新建一个结点并赋值
        nod.next = self.head  # 结点指针域指向第一个结点
        self.head = nod  # 头结点指针指向当前结点

    def tailcreatelist(self, item):
        nod = linknode(item)  # 新建一个结点并赋值,指针域为None
        cur = self.head
        while cur.next != None:  # 遍历到最后一个元素,指针域为空
            cur = cur.next
        cur.next = nod  # nod成为最后一个结点



if __name__ == "__main__":
    ll1=linklist()
    # for i in range(10):
    #     ll1.headcreatlist(i*10)
    #
    # len=ll1.listlength()
    # print("单链表的长度为:",len)
    # sh=ll1.tralist()
    # print("头插法建立的链表遍历为:",ll1.tralist())

    # ll2 = linklist()
    for i in range(10):
        ll1.tailcreatelist(i * 100)

    len = ll1.listlength()
    print("单链表的长度为:", len)
    sh = ll1.tralist()
    print("尾插法插法建立的链表遍历为:", ll1.tralist())

报错语句为:

while cur.next != None: # 遍历到最后一个元素,指针域为空

这是因为尾插法建立链表时,插入第一个元素时,self.head是指向第一个元素的,此时为None,所以没有next属性,自然就会报错。
因此第一个结点需要特殊处理,我们一般通过增加头结点的方式来避免这种特殊处理。Python实现单链表(带头结点)可以通过增加头结点的方式,还可以尾插法时保证表不为空即可(上面注释的代码取消注释)。

猜你喜欢

转载自blog.csdn.net/liulanba/article/details/113767926
今日推荐