In: Computer Science
Python:
Solve following problems using Linked List Data Structure
2. Create a Queue class. In the queue class create enqueue, dequeue, first, empty, len and resize methods. The class should support circular queue and have the ability to resize the queue.
ANS:
# Online Python compiler (interpreter) to run Python
online.
# Write Python 3 code in this online editor and run it.
class Node:
def __init__(self):
self.item=None
self.linked=None
class CQueue:
def __init__(self):
front=None
rear=None
#This is enqueue which will make circular queue
def Enqueue(q,value):
temp=Node()
temp.item=value
if(q.front==None):
q.front=temp
else:
q.rear.linked=temp
q.rear=temp
q.rear.linked=q.front
#deleting element from Circular queue
def Dequeue(q):
if(q.front==None):
print("Queue Empty!")
return -1000
value=None
if(q.front==q.rear):
value=q.front.item
q.front=None
q.rear=None
else:
temp=q.front
value=temp.item
q.front=q.front.linked
q.rear.linked=q.front
return value
def first(q):
return q.front
def display(q):
temp=q.front
print("Circular Queue Elements:")
while(temp.linked!=q.front):
print(temp.item, end=" ")
temp=temp.linked
print(temp.item)
if __name__ == '__main__':
q = CQueue()
q.front = q.rear = None
Enqueue(q, 20)
Enqueue(q, 18)
Enqueue(q, 9)
Enqueue(q,12)
#print("First=",first(q))
display(q)
print("Deleted value = ", Dequeue(q))
print("Deleted value = ", Dequeue(q))
display(q)
Enqueue(q, 100)
Enqueue(q, 80)
display(q)
COMMENT DOWN FOR ANY QUERIES!!!
HIT A THUMBS UP IF YOU DO LIKE IT!!!