社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

利用python中的单链表实现队列中的AttributeError

Mahzad • 3 年前 • 1269 次点击  

我想通过使用单个链表实现一个队列。当我运行下面的代码时,我收到AttributeError。我不知道该怎么解决这个问题。 我假设链表的第一个是队列的前面,第二个是队列的后面。 通过使用while循环,我想连接整个单链表。

class Node:
    def __init__(self, value):
        self.info = value
        self.link = None


class Queue:
    def __init__(self):
        self.front = None


    def enqueue(self, data):
        temp = Node(data)
        p = self.front
        if self.front is None:
            self.front = temp

        while p.link is not None:
            p = p.link
        p.link = temp
        temp.link = None

    def dequeue(self):
        self.front = self.front.link

    def size(self):
        p = self.start
        n = 0
        while p is not None:
            p = p.link
            n += 1
        return n

    def display(self):
        p = self.start
        while p is not None:
            p = p.link
        print(p.info, '', end='')

qu = Queue()

for i in range(4):
    add = int(input("please enter the elements "))
    qu.enqueue(add)
    qu.display()

for i in range(2):
    qu.dequeue()
    qu.display()
Traceback (most recent call last):
  File "C:/Users/HP/Music/Queue_SLList.py", line 43, in <module>
    qu.enqueue(add)
  File "C:/Users/HP/Music/Queue_SLList.py", line 18, in enqueue
    while p.link is not None:
AttributeError: 'NoneType' object has no attribute 'link'
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133851
 
1269 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Barmar
Reply   •   1 楼
Barmar    3 年前

当队列为空时,可以设置 p None 当你这么做的时候 p = self.front .然后,当你尝试这样做时,会出现错误 while p.link is not None 因为 P 不是节点。

如果你在排队等待第一个noe,你应该从方法返回。

    def enqueue(self, data):
        temp = Node(data)
        if self.front is None:
            self.front = temp
            return

        p = self.front
        while p.link is not None:
            p = p.link
        p.link = temp
        temp.link = None