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

When using Python to implement a linear table, if you encounter a problem, use the tail interpolation method to create a singly linked list (there is no element in the table), and an error will be reported: 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())

The error statement is:

while cur.next != None: # Traverse to the last element, the pointer field is empty

This is because when the tail insertion method creates a linked list, when inserting the first element, self.head points to the first element, which is None at this time, so there is no next attribute, and an error will naturally be reported.
Therefore, the first node needs special processing, and we generally avoid this special processing by increasing the head node. Python implements a singly linked list (lead node) by adding a head node, and you can also ensure that the table is not empty when you insert the tail (uncomment the code commented above).

Guess you like

Origin blog.csdn.net/liulanba/article/details/113767926