0

I want to implement a queue by using a single linked list. When I run the below code, I receive the AttributeError. I don't know what should I do to fix this issue. I assume the first of the linked list as a front and the of that as a rear of the queue. by using the while loop I wanted to concatenate the whole single linked list.

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'
Mahzad
  • 13
  • 3
  • `p = self.front` needs to be *after* the `if` that sets `self.front` – Barmar Oct 19 '21 at 19:37
  • Here you are @Barmar Traceback (most recent call last): File "C:/Users/HP/Music/Queue_SLList.py", line 43, in 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' – Mahzad Oct 19 '21 at 19:38
  • Put it in the question so it can be formatted readably. – Barmar Oct 19 '21 at 19:39

1 Answers1

0

When the queue is empty, you set p to None when you do p = self.front. Then you get an error when you try to do while p.link is not None because p isn't a node.

You should just return from the method in the case where you're enqueuing the first 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
Barmar
  • 741,623
  • 53
  • 500
  • 612