pythonqueuesingly-linked-listenqueue

AttributeError in the implementation of queue by using Single Linked List in the python


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'

Solution

  • 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