#an exception to be raised by an empty Queue
class Empty(Exception):
pass
class Queue:
class _Node:
def __init__(self, e, n):
self._element = e #Users element
self._next = n #The next node in the list
def __init__(self):
self._head = None #Reference the first node
self._tail = None #refernce the last node
self._size = 0 #The number of elements in the queue
def __len__(self):
return self._size
def is_empty(self):
return len(self) == 0
def first(self):
if self.is_empty():
raise Empty("Queue is empty.")
return self._head._element
def enqueue(self, e):
#add a new element at the back
newnode = self._Node(e, None)
if self.is_empty():
self._head = newnode #if the queue is empty, the newnode becomes the head
else:
self._tail._next = newnode #if the queue is not empty, the last node points to the new node
self._tail = newnode #The new node becomes the tail
self._size += 1
def dequeue(self):
if self.is_empty():
raise Empty("Queue is empty.")
element = self._head._element
self._head = self._head._next # Make the next node the new head
self._size -= 1
return element
# test the stack
Q = Queue()
Q.enqueue(100)
Q.enqueue(200)
Q.enqueue(300)
Q.enqueue(400)
Q.enqueue(500)
print("Size: ", len(Q))
print(Q.first())
while not Q.is_empty():
print(Q.dequeue())
print("Size:", len(Q))