Python3: AttributeError: el objeto 'NoneType' no tiene atributo 'next'

Si encuentra un problema con la tabla lineal usando Python y usa el método de interpolación de cola para crear una lista enlazada individualmente (no hay ningún elemento en la tabla), se informará un error: AttributeError: el objeto 'NoneType' no tiene atributo ' próximo'

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())

La declaración de error es:

while cur.next! = None: # Recorre al último elemento, el campo del puntero está vacío

Esto se debe a que cuando el método de inserción de cola crea una lista vinculada, al insertar el primer elemento, self.head apunta al primer elemento, que es Ninguno en este momento, por lo que no hay un atributo siguiente y, naturalmente, se informará un error.
Por lo tanto, el primer nodo necesita un procesamiento especial, y generalmente evitamos este procesamiento especial aumentando el nodo principal. Python implementa una lista enlazada individualmente (nodo principal) agregando un nodo principal, y también puede asegurarse de que la tabla no esté vacía al insertar la cola (descomente el código comentado anteriormente).

Supongo que te gusta

Origin blog.csdn.net/liulanba/article/details/113767926
Recomendado
Clasificación