Implementation of Queue in Python List

#Queue Implementation in Python List

#Function to check the queue is empty or not.
def isEmpty(Qu):
    if Qu==[]:
        return True
    else:
        return False


#Function to insert the value in the queue.
def EnQueue(Qu,val):
    Qu.append(val)
    if len(Qu)==1:
        front=rear=0
    else:
        rear=len(Qu)-1

#Function to remove the value from the front of the queue
def DeQueue(Qu):
    if isEmpty(Qu):
        return "Underflow"
    else:
        val=Qu.pop(0)
    if len(Qu)==0:
        front=rear=None
    return val


#Function to inspect the position of the front in queue
def Peek(Qu):
    if isEmpty(Qu):
        return "Underflow"
    else:
        front=0
    return Qu[front]


#Function to display the queue values
def Display(Qu):
    if isEmpty(Qu):
        print("Queue is Empty, Nothing to display")
    elif len(Qu)==1:
        print(Qu[0],"<==Front,rear")
    else:
        front=0
        rear=len(Qu)-1
        print(Qu[0],"<==Front")
        for i in range(1,rear):
            print(Qu[i])
        print(Qu[rear],"<==Rear")


#__main__
queue=[]        #Initially queue is empty list
front=None

while True:
    print("QUEUE OPERATION MENU")
    print("1. Enqueue")
    print("2. Dequeue")
    print("3. Peek")
    print("4. Display")
    print("5. Exit")
    ch=int(input("Enter your choice: "))

    if ch==1:
        n=int(input("Enter value: "))
        EnQueue(queue,n)

    elif ch==2:
        n=DeQueue(queue)
        if n=="Underflow":
            print("Underflow!!! queue is empty")
        else:
            print("Deleted value is:",n)

    elif ch==3:
        n=Peek(queue)
        if n=="Underflow":
            print("Underflow!!! queue is empty")
        else:
            print("Front value is:",n)

    elif ch==4:
        Display(queue)

    elif ch==5:
        break;

    else:
        print("Invalid choice")


Output:

QUEUE OPERATION MENU
1. Enqueue
2. Dequeue
3. Peek
4. Display
5. Exit
Enter your choice: 



No comments

Post your comments

Powered by Blogger.