Queue in Python
A queue is a linear dynamic data structure that follows First-In/First-Out (FIFO) principle. In a queue, addition of a new element and deletion of an element occurs at different end which implies that the element which is added first in the queue will be the first to be removed from the queue.
Features of queue
- It is a dynamic data structure.
- It has dynamic size.
- It uses dynamic memory allocation.
Operations of a queue
- isEmpty(): Checks whether the queue is empty or not.
- size(): Returns the size of the queue.
- frontElement(): Returns the front element of the queue. It is the element which will be dequeued next.
- rearElement(): Returns the rear element of the queue. It is the element behind which next element will be enqueued.
- EnQueue(x): Adds a new element ‘x’ from the rear side of the queue. Consequently, size of the queue increases by 1.
- DeQueue(): Deletes the front element of the queue. Consequently, size of the queue decreases by 1.
Implementation of queue
# function to create queue def CreateQueue(): queue = [] return queue # create function to check whether # the queue is empty or not def isEmpty(queue): if(len(queue) == 0): print("Queue is empty.") else: print("Queue is not empty.") #create function to return size of the queue def size(queue): return len(queue) #create function to add new element def EnQueue(queue, newElement): queue.append(newElement) print(newElement, "is added into the queue.") #create function to delete front element def DeQueue(queue): print(queue.pop(0), "is deleted from the queue.") #create function to get front element def frontElement(queue): return queue[0] #create function to get rear element def rearElement(queue): return queue[len(queue) - 1] # test the code MyQueue = CreateQueue() EnQueue(MyQueue, 10) EnQueue(MyQueue, 20) EnQueue(MyQueue, 30) EnQueue(MyQueue, 40) DeQueue(MyQueue) isEmpty(MyQueue)
The above code will give the following output:
10 is added into the queue. 20 is added into the queue. 30 is added into the queue. 40 is added into the queue. 10 is deleted from the queue. Queue is not empty.
Recommended Pages
- Python Program - To Check Prime Number
- Python Program - Bubble Sort
- Python Program - Selection Sort
- Python Program - Maximum Subarray Sum
- Python Program - Reverse digits of a given Integer
- Python - Swap two numbers
- Python Program - Fibonacci Sequence
- Python Program - Insertion Sort
- Python Program - Find Factorial of a Number
- Python Program - Find HCF of Two Numbers
- Python Program - To Check Whether a Number is Palindrome or Not
- Python Program - To Check Whether a String is Palindrome or Not
- Python Program - Heap Sort
- Python Program - Quick Sort
- Python - Swap Two Numbers without using Temporary Variable
- Python Program - To Check Armstrong Number
- Python Program - Counting Sort
- Python Program - Radix Sort
- Python Program - Find Largest Number among Three Numbers
- Python Program - Print Floyd's Triangle