To dequeue, we will first store the item which we are going to delete from the queue in a variable because we will be returning it at last. If the queue is empty, then we will throw an error. To dequeue, we will first check if the queue is empty or not. Otherwise, we will just increase the tail by 1. While adding the element, it might be possible that we have added the element at the last of the array and in this case, the tail will go to the first element of the array. If the queue is not full, we will add the element to the tail i.e, Q = x. To enqueue any item to the queue, we will first check if the queue is full or not i.e., Now, we have to deal with the enqueue and the dequeue operations. Similarly, we will say that if the head of a queue is 1 more than the tail, the queue is full. We can easily check if a queue is empty or not by checking if head and tail are pointing to the same location or not at any time. Initially, the queue will be empty i.e., both head and tail will point to the same location i.e., at index 1. In this case, our tail will point to the first element of the array and will follow a circular order. Suppose tail is at the last element of the queue and there are empty blocks before head as shown in the picture given below. To insert any element, we add that element at tail and increase the tail by one to point to the next element of the array. head will always point to the oldest element which was added and tail will point where the new element is going to be added. We will maintain two pointers - tail and head to represent a queue.
0 Comments
Leave a Reply. |