Reputation: 89
I'm creating a program to create a queue and add,delete and display elements. For this I create a list, then take input from users and append the same number of 0s and then proceed normally. The problem arises that the value of rear and front does not change and remains constant which leads to it not displaying and also not filling up.
How can I fix this.
l=[]
global front
global rear
front=-1
rear=-1
print("Enter the number of elements ")
maxsize=int(input())
i=0
q=0
for q in range(0,maxsize): #for creating an array with user input number of 0s
l.append(0)
def isFull():
if(rear==maxsize):
return 1
else:
return 0
def isEmpty():
if(front==-1 and rear==-1):
return 1
elif(front==rear):
return 1
else:
return 0
def enqueue(n):
if(isEmpty()==1):
front=0
rear=0
l[rear]=n
rear=rear+1
else:
l[rear]=n
rear=rear+1
def dequeue():
if(isEmpty()==1):
return 1
else:
front=front+1
while(i==0):
print("Add an element ?(0) \nDelete an element?(1) \nDisplay the
elements?(2)\n")
a=int(input())
if(a==0):
if(isFull()==1):
print("Queue is full")
else:
b=int(input())
enqueue(b)
if(a==1):
dequeue()
if(a==2):
for c in range(front,rear):
print(l[c])
Upvotes: 2
Views: 941
Reputation: 435
You have to redeclare the global variables (front,rear in this case) at the start of any methods using them. Like this
def enqueue(n):
global front
global rear
if(isEmpty()==1):
front=0
rear=0
l[rear]=n
rear=rear+1
else:
l[rear]=n
rear=rear+1
Upvotes: 1