2

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])
4
  • 1
    Do you have a homework assignment to create a queue, or do you just need a queue for some other task? If the latter, just use collections.deque, which already has methods you can use to efficiently add elements to one end and remove elements from the other. Commented Jan 28, 2019 at 16:04
  • It is an assignment where I have to use the standard functions Commented Jan 28, 2019 at 16:06
  • @NamanSood, did I answer your question? Commented Jan 29, 2019 at 15:04
  • @MayankMehtani yes thank's a lot it solved all of my errors Commented Jan 30, 2019 at 6:33

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.