Unit - 3
Stack and Queue
Q1) What is stack?
A1) A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Stack has one end, whereas the Queue has two ends (front and rear). It contains only one pointer (top pointer) pointing to the topmost element of the stack. Whenever an element is added in the stack, it is added on the top of the stack, and the element can be deleted only from the stack. In other words, a stack can be defined as a container in which insertion and deletion can be done from the one end known as the top of the stack.
Some key points related to stack
● It is called as stack because it behaves like a real-world stack, piles of books, etc.
● A Stack is an abstract data type with a predefined capacity, which means that it can store the elements of a limited size.
● It is a data structure that follows some order to insert and delete the elements, and that order can be LIFO or FILO.
Stack Representation
A stack and its operations are depicted in the diagram below.
Fig 1: Stack representation
Array, Structure, Pointer, and Linked List can all be used to create a stack. A stack can be either fixed in size or dynamically resized. We'll use arrays to implement stack here, making it a fixed-size stack implementation.
Q2) Write about push operation?
A2) PUSH operation
The steps involved in the PUSH operation is given below:
● Before inserting an element in a stack, we check whether the stack is full.
● If we try to insert the element in a stack, and the stack is full, then the overflow condition occurs.
● When we initialize a stack, we set the value of top as -1 to check that the stack is empty.
● When the new element is pushed in a stack, first, the value of the top gets incremented, i.e., top=top+1, and the element will be placed at the new position of the top.
● The elements will be inserted until we reach the max size of the stack.
Fig 2: Push Operation Example
Q3) What is poop operation?
A3) POP operation
The steps involved in the POP operation is given below:
● Before deleting the element from the stack, we check whether the stack is empty.
● If we try to delete the element from the empty stack, then the underflow condition occurs.
● If the stack is not empty, we first access the element which is pointed by the top
● Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.
Fig 3: Pop Operation example
Q4) Write short notes on peek operation?
A4) Peek operation
Peek() is a stack action that returns the value of the stack's topmost element without removing it.
The peek operation retrieves the topmost element in the stack without removing it from the data element collections.
A peek operation's algorithm is as follows:
Begin to peek
Return stack[top];
End
The peek operation is implemented as follows:
Int peek()
{
Return stack[top];
}
Q5) How does the array implement the stack?
A5) The stack is created using the array in array implementation. Arrays are used to accomplish all of the operations on the stack. Let's look at how each operation can be accomplished utilizing an array data structure on the stack.
Adding an element onto the stack (push operation)
A push operation occurs when an element is added to the top of a stack. Two steps are involved in a push operation.
- Increase the value of the variable Top to allow it to refer to the next memory address.
- Add an element to the top of the incremented list. Adding a new element to the top of the stack is referred to as this.
When we try to put an element into a totally loaded stack, the stack overflows. As a result, our main function must always avoid stack overflow.
Algorithm
Begin
if top = n then stack full
top = top + 1
stack (top) : = item;
End
Implementation
Void push (int val,int n) //n is size of the stack
{
if (top == n )
cout<<"\n Overflow";
else
{
top = top +1;
stack[top] = val;
}
}
Deletion of an element from a stack (Pop operation)
The pop action removes an element from the top of the stack. When an item is removed from the stack, the value of the variable top is increased by one. The stack's topmost element is saved in a separate variable, and then the top is decremented by one. As a result, the operation returns the removed value that was previously saved in another variable.
When we try to delete an element from an already empty stack, we get an underflow condition.
Algorithm
Begin
if top = 0 then stack empty;
item := stack(top);
top = top - 1;
End;
Implementation
Int pop ()
{
if(top == -1)
{
cout<<"Underflow";
return 0;
}
else
{
return stack[top - - ];
}
}
Visiting each element of the stack (Peek operation)
Returning the element at the top of the stack without removing it is known as a peek operation. If we try to return the top piece from an already empty stack, we may encounter an underflow problem.
Algorithm
PEEK (STACK, TOP)
Begin
if top = -1 then stack empty
item = stack[top]
return item
End
Implementation
Int peek()
{
if (top == -1)
{
cout<<"Underflow";
return 0;
}
else
{
return stack [top];
}
}
Q6) How does the linked list implement the stack?
A6) Linked list Implementation
To implement stack, we can use a linked list instead of an array. The memory is dynamically allocated with a linked list. However, the temporal complexity of all operations, such as push, pop, and peek, is the same in all scenarios.
The nodes in a linked list implementation of a stack are kept in memory in a non-contiguous manner. Each node on the stack has a pointer to its immediate successor node. If there isn't enough room in the memory heap to create a node, the stack is said to have overflown.
Fig 4: Linked list
Adding a node to the stack (Push operation)
The address field of the topmost node in the stack is always null. Let's look at how each action is carried out in the stack's linked list implementation.
The push action is used to add a node to the stack. Pushing an element to a stack in a linked list differs from pushing an element to a stack in an array. The following procedures are required to push an element onto the stack.
- First, make a node and allocate memory to it.
- If the list is empty, the item should be moved to the top as the list's first node. This involves giving the data component of the node a value and giving the address part of the node a null value.
- If the list already has some nodes, we must place the new element at the beginning of the list (to not violate the property of the stack). Assign the address of the starting element to the address field of the new node for this purpose, and make the new node the list's starting node.
Implementation
Void push ()
{
int val;
struct node *ptr =(struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
cout<<"not able to push the element";
}
else
{
cout<<"Enter the value";
scanf("%d",&val);
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;
}
cout<<"Item pushed";
}
}
Deleting a node from the stack (POP operation)
The pop operation is used to remove a node from the top of the stack. The deletion of a node from the stack's linked list implementation differs from the array implementation. To remove an element from the stack, we must first perform the following steps:
- Check for the underflow condition - When we try to pop from an already empty stack, we get an underflow problem. If the list's head pointer points to null, the stack will be empty.
- Adjust the head pointer accordingly - Because the elements in a stack are only popped from one end, the value stored in the head pointer must be removed, and the node must be released. The head node's next node now serves as the head node.
Implementation
Void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
cout<<"Underflow";
}
else
{
item = head->val;
ptr = head;
head = head->next;
free(ptr);
cout<<"Item popped";
}
}
Q7) What is the application of stack?
A7) The following are the applications of the stack:
● Balancing of symbols: Stack is used for balancing a symbol. For example, we have the following program:
- Int main()
- {
- cout<<"Hello";
- coût<<"java point";
- }
As we know, each program has an opening and closing braces; when the opening braces come, we push the braces in a stack, and when the closing braces appear, we pop the opening braces from the stack. Therefore, the net value comes out to be zero. If any symbol is left in the stack, it means that some syntax occurs in a program.
● String reversal: Stack is also used for reversing a string. For example, we want to reverse a "java point" string, so we can achieve this with the help of a stack.
First, we push all the characters of the string in a stack until we reach the null character. After pushing all the characters, we start taking out the character one by one until we reach the bottom of the stack.
● UNDO/REDO: It can also be used for performing UNDO/REDO operations. For example, we have an editor in which we write 'a', then 'b', and then 'c'; therefore, the text written in an editor is abc. So, there are three states, a, ab, and abc, which are stored in a stack. There would be two stacks in which one stack shows UNDO state, and the other shows REDO state.
If we want to perform a UNDO operation, and want to achieve an 'ab' state, then we implement a pop operation.
● Recursion: The recursion means that the function is calling itself again. To maintain the previous states, the compiler creates a system stack in which all the previous records of the function are maintained.
● DFS(Depth First Search): This search is implemented on a Graph, and Graph uses the stack data structure.
● Backtracking: Suppose we have to create a path to solve a maze problem. If we are moving in a particular path, and we realize that we come on the wrong way. In order to come at the beginning of the path to create a new path, we have to use the stack data structure.
● Expression conversion: Stack can also be used for expression conversion. This is one of the most important applications of stack. The list of the expression conversion is given below:
● Infix to prefix
● Infix to postfix
● Prefix to infix
● Prefix to postfix
● Postfix to infix
● Memory management: The stack manages the memory. The memory is assigned in the contiguous memory blocks. The memory is known as stack memory as all the variables are assigned in a function called stack memory. The memory size assigned to the program is known to the compiler. When the function is created, all its variables are assigned in the stack memory. When the function completes its execution, all the variables assigned in the stack are released.
Q8) What is recursion?
A8) The process through which a function calls itself is known as recursion. We utilize recursion to break down larger issues into smaller ones. One thing to keep in mind is that the recursive technique can only be used if each sub-problem follows the same patterns.
There are two pieces to a recursive function. The recursive case and the base case. The basic case is utilized to finish the repeating task. If the base case isn't specified, the function will repeat indefinitely.
When we call a function in a computer program, the value of the program counter is saved in the internal stack before we jump into the function area. It pulls out the address and assigns it to the program counter after completing the operation, then resumes the task. It will save the address several times throughout a recursive call and then jump to the next function call statement. If one of the base cases isn't declared, it will repeat over and over, storing the address in the stack. If the stack runs out of space, it will throw an error called "Internal Stack Overflow."
Finding the factorial of a number is an example of a recursive call. The factorial of an integer n = n! is the same as n * (n-1)!, as we can see. , which is same to n * (n - 1) * (n - 2)! So, if factorial is a function, it will be run repeatedly, but the parameter will be reduced by one. It will return 1 if the parameter is 1 or 0. This could be the recursion's starting point.
Example
#include<iostream>
Using namespace std;
Long fact(long n){
if(n <= 1)
return 1;
return n * fact(n-1);
}
Main(){
cout << "Factorial of 6: " << fact(6);
}
Output
Factorial of 6: 720
Q9) How to convert infix to prefix expression with an example?
A9) Rules for the conversion of infix to prefix expression:
● To begin, invert the infix statement in the problem.
● From left to right, scan the expression.
● Print the operands as soon as they arrive.
● If the operator arrives and the stack is empty, simply place the operator on top of the stack.
● Push the incoming operator onto the stack if the incoming operator has a greater priority than the TOP of the stack.
● Push the incoming operator onto the stack if the incoming operator has the same precedence as a TOP of the stack.
● Pop and print the top of the stack if the incoming operator has a lower priority than the TOP of the stack. Test the incoming operator against the top of the stack once again, then pop it off the stack until it finds an operator with a lower or equal precedence.
● If the incoming operator and the top of the stack have the same precedence and the incoming operator is, pop the top of the stack until the condition is true. Push the operator if the condition isn't true.
● Pop and print all the operators from the top of the stack when we reach the end of the expression.
● Push it into the stack if the operator is ')'.
● If the operator is '(,' then it will pop all the operators from the stack until it finds an opening bracket.
● Push the operator onto the stack if the top of the stack is ')'.
● Reverse the output at the end.
Example
K + L - M * N + (O^P) * W/U/V * T + Q
If we want to transform an infix expression to a prefix expression, we must first reverse the expression.
The inverse expression is as follows:
Q + T * V/U/W * ) P^O(+ N*M - L + K
We've established a table with three columns: input expression, stack, and prefix expression, in order to get the prefix expression. Any symbol that we come across is simply added to the prefix expression. If we come across the operator, we'll add it to the stack.
Input expression | Stack | Prefix expression |
Q |
| Q |
+ | + | Q |
T | + | QT |
* | +* | QT |
V | +* | QTV |
/ | +*/ | QTV |
U | +*/ | QTVU |
/ | +*// | QTVU |
W | +*// | QTVUW |
* | +*//* | QTVUW |
) | +*//*) | QTVUW |
P | +*//*) | QTVUWP |
^ | +*//*)^ | QTVUWP |
O | +*//*)^ | QTVUWPO |
( | +*//* | QTVUWPO^ |
+ | ++ | QTVUWPO^*//* |
N | ++ | QTVUWPO^*//*N |
* | ++* | QTVUWPO^*//*N |
M | ++* | QTVUWPO^*//*NM |
- | ++- | QTVUWPO^*//*NM* |
L | ++- | QTVUWPO^*//*NM*L |
+ | ++-+ | QTVUWPO^*//*NM*L |
K | ++-+ | QTVUWPO^*//*NM*LK |
|
| QTVUWPO^*//*NM*LK+-++ |
The expression QTVUWPO*/*NM*LK+-++, for example, is not a final expression. To get the prefix expression, we must reverse this expression.
Q10) How to Convert of infix to postfix explained with an example?
A10) To convert an infix expression to a prefix expression, we'll use the stack data structure. We push operators into the stack whenever they are encountered. If an operand is encountered, the operand is appended to the expression.
Rules for the conversion from infix to postfix expression
● As the operands arrive, print them.
● Push the incoming operator onto the stack if the stack is empty or has a left parenthesis on top.
● Push the incoming symbol to the stack if it is '('.
● Pop the stack and print the operators until the left parenthesis is discovered if the entering symbol is ')'.
● If the incoming symbol has a greater priority than the top of the stack, it should be pushed to the top.
● Pop and print the top of the stack if the incoming symbol has a lower priority than the top of the stack. Then compare the incoming operator to the new stack's top.
● Use the associativity rules if the incoming operator has the same precedence as the top of the stack. If the associativity is left to right, pop and print the top of the stack before pushing the inbound operator. Push the incoming operator if the associativity is from right to left.
● Pop and print all of the stack's operators at the end of the expression.
Example
Infix expression: K + L - M*N + (O^P) * W/U/V * T + Q
Input Expression | Stack | Postfix Expression |
K |
| K |
+ | + |
|
L | + | K L |
- | - | K L+ |
M | - | K L+ M |
* | - * | K L+ M |
N | - * | K L + M N |
+ | + | K L + M N* K L + M N* - |
( | + ( | K L + M N *- |
O | + ( | K L + M N * - O |
^ | + ( ^ | K L + M N* - O |
P | + ( ^ | K L + M N* - O P |
) | + | K L + M N* - O P ^ |
* | + * | K L + M N* - O P ^ |
W | + * | K L + M N* - O P ^ W |
/ | + / | K L + M N* - O P ^ W * |
U | + / | K L + M N* - O P ^W*U |
/ | + / | K L + M N* - O P ^W*U/ |
V | + / | KL + MN*-OP^W*U/V |
* | + * | KL+MN*-OP^W*U/V/ |
T | + * | KL+MN*-OP^W*U/V/T |
+ | + | KL+MN*-OP^W*U/V/T* KL+MN*-OP^W*U/V/T*+ |
Q | + | KL+MN*-OP^W*U/V/T*Q |
|
| KL+MN*-OP^W*U/V/T*+Q+ |
KL+MN*-OPW*U/V/T*+Q+ is the ultimate postfix expression of infix expression(K + L - M*N + (OP) * W/U/V * T + Q).
Q11) Define queue?
A11) A queue is an ordered list that allows insert operations to be done at one end (REAR) and delete operations to be performed at the other end (FRONT). The First In First Out list is referred to as a queue.
For example, create a queue, People in line for a train ticket.
Fig 5: Queue
Operation on queue
● Add (Enqueue) - The enqueue action is used to add the element to the queue's backend. It gives a void result.
● Delete (Dequeue) - The dequeue operation is used to remove items from the queue's front end. It also returns the front-end element that has been removed. It gives you an integer value as a result. It's also possible to make the dequeue operation void.
● Full (queue overflow) - When the Queue is totally full, the overflow condition appears.
● Empty (queue underflow) - The underflow condition is thrown when the Queue is empty, that is, when there are no elements in the Queue.
Q12) Write about insertion operation of queue?
A12) Insertion operation
By adding an element to the end of the queue, the insert operation appends it. The new element will be the queue's last element.
To begin, use the following line to allocate memory for the new node ptr.
Ptr = (struct node *) malloc (sizeof(struct node));
There are two possible scenarios for adding this new node ptr to the connected queue.
We inject an element into an empty queue in the first scenario. The condition front = NULL gets true in this scenario.
The queue in the second scenario has more than one element. The condition front = NULL is no longer true. We need to change the end pointer rear in this case such that the next pointer of rear points to the new node ptr. Because this is a linked queue, the rear pointer must also point to the newly inserted node ptr. We must additionally set the rear pointer's next pointer to NULL.
Algorithm
● Step 1: Allocate the space for the new node PTR
● Step 2: SET PTR -> DATA = VAL
● Step 3: IF FRONT = NULL
SET FRONT = REAR = PTR
SET FRONT -> NEXT = REAR -> NEXT = NULL
ELSE
SET REAR -> NEXT = PTR
SET REAR = PTR
SET REAR -> NEXT = NULL
[END OF IF]
● Step 4: END
Function
Void insert(struct node *ptr, int item; )
{
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
cout<<"\nOVERFLOW\n";
return;
}
else
{
ptr -> data = item;
if(front == NULL)
{
front = ptr;
rear = ptr;
front -> next = NULL;
rear -> next = NULL;
}
else
{
rear -> next = ptr;
rear = ptr;
rear->next = NULL;
}
}
}
Q13) What is the Deletion operation in queue?
A13) The deletion action removes the initial inserted element from all queue elements. To begin, we must determine whether the list is empty or not. If the list is empty, the condition front == NULL becomes true; in this case, we simply write underflow on the console and quit.
Otherwise, the element pointed by the pointer front will be deleted. Copy the node pointed by the front pointer into the pointer ptr for this purpose. Shift the front pointer to the next node and release the node referenced by node ptr. The following statements are used to do this.
Algorithm
● Step 1: IF FRONT = NULL
Write " Underflow "
Go to Step 5
[END OF IF]
● Step 2: SET PTR = FRONT
● Step 3: SET FRONT = FRONT -> NEXT
● Step 4: FREE PTR
● Step 5: END
Function
Void delete (struct node *ptr)
{
if(front == NULL)
{
cout<<"\nUNDERFLOW\n";
return;
}
else
{
ptr = front;
front = front -> next;
free(ptr);
}
}
Q14) Explain the array implementation of queue?
A14) Using linear arrays, we can easily describe a queue. In the case of every queue, there are two variables to consider: front and back. In a queue, the front and back variables indicate the location from which insertions and deletions are made. The initial value of front and queue is -1, which indicates that the queue is empty. The next figure shows an array representation of a queue with 5 elements and their respective front and rear values.
Fig 6: Queue
The line of characters that make up the English word "HELLO" is depicted in the diagram above. Because no deletions have been made in the queue to date, the value of front remains -1. When an insertion is performed in the queue, however, the value of rear increases by one. After entering one element into the queue depicted in the above picture, the queue will appear as follows. The value of the rear will increase to 5, while the value of the front will remain unchanged.
Fig 7: Queue after inserting element
The value of front will grow from -1 to 0 if an element is deleted. The queue, on the other hand, will resemble the following.
Fig 8: Queue after deleting element
Algorithm to insert any element in a queue
Compare rear to max - 1 to see if the queue is already full. If this is the case, an overflow error will be returned.
If the item is to be inserted as the first element in the list, set the front and back values to 0 and insert the item at the back end.
Otherwise, keep increasing the value of rear and inserting each element with rear as the index one by one.
Algorithm
Step 1: IF REAR = MAX - 1
Write OVERFLOW
Go to step
[END OF IF]
Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE
SET REAR = REAR + 1
[END OF IF]
Step 3: Set QUEUE[REAR] = NUM
Step 4: EXIT
Function
Void insert (int queue[], int max, int front, int rear, int item)
{
if (rear + 1 == max)
{
cout<<"overflow";
}
else
{
if(front == -1 && rear == -1)
{
front = 0;
rear = 0;
}
else
{
rear = rear + 1;
}
queue[rear]=item;
}
}
Algorithm to delete an element from the queue
Write an underflow message and leave if the value of front is -1 or greater than the value of rear.
Otherwise, keep increasing the front's value and returning the item at the front of the queue each time.
Algorithm
● Step 1: IF FRONT = -1 or FRONT > REAR
Write UNDERFLOW
ELSE
SET VAL = QUEUE[FRONT]
SET FRONT = FRONT + 1
[END OF IF]
● Step 2: EXIT
Function
Int delete (int queue[], int max, int front, int rear)
{
int y;
if (front == -1 || front > rear)
{
cout<<"underflow";
}
else
{
y = queue[front];
if(front == rear)
{
front = rear = -1;
else
front = front + 1;
}
return y;
}
}
Q15) Write about linked list implementation of queue?
A15) The array method cannot be used for large scale applications when queues are established due to the limitations. The linked list version of queue is one of the alternatives to array implementation.
Each node of a linked queue is made up of two parts: the data part and the link part.
In the memory of the linked queue, there are two pointers: front pointer and rear pointer. The front pointer contains the location of the queue's first element, while the back pointer contains the address of the queue's last member.
The linked depiction of the queue is depicted in the diagram below.
Fig 9: Linked queue
Example in C++
#include <iostream>
Using namespace std;
Struct node {
Int data;
Struct node *next;
};
Struct node* front = NULL;
Struct node* rear = NULL;
Struct node* temp;
Void Insert(int val) {
If (rear == NULL) {
Rear = new node;
Rear->next = NULL;
Rear->data = val;
Front = rear;
} else {
Temp=new node;
Rear->next = temp;
Temp->data = val;
Temp->next = NULL;
Rear = temp;
}
}
Void Delete() {
Temp = front;
If (front == NULL) {
Cout<<"Queue is empty!!"next;
Cout<<"Element deleted from queue is : "next;
}
Cout<;
}
Output:
Queue Created:
10 20 30 40 50
Element deleted from queue is: 10
Queue after one deletion:
20 30 40 50
Q16) Describe a circular queue?
A16) Why was the concept of the circular queue introduced?
There was one limitation in the array implementation of Queue. If the rear reaches to the end position of the Queue then there might be the possibility that some vacant spaces are left in the beginning which cannot be utilized. So, to overcome such limitations, the concept of the circular queue was introduced.
Fig 10: Circular queue
As we can see in the above image, the rear is at the last position of the Queue and the front is pointing somewhere rather than the 0th position. In the above array, there are only two elements and the other three positions are empty. The rear is at the last position of the Queue; if we try to insert the element then it will show that there are no empty spaces in the Queue. There is one solution to avoid such wastage of memory space by shifting both the elements at the left and adjust the front and rear end accordingly. It is not a practically good approach because shifting all the elements will consume lots of time. The efficient approach to avoid the wastage of the memory is to use the circular queue data structure.
What is a Circular Queue?
A circular queue is similar to a linear queue as it is also based on the FIFO (First In First Out) principle except that the last position is connected to the first position in a circular queue that forms a circle. It is also known as a Ring Buffer.
Operations on Circular Queue
The following are the operations that can be performed on a circular queue:
● Front: It is used to get the front element from the Queue.
● Rear: It is used to get the rear element from the Queue.
● enQueue(value): This function is used to insert the new value in the Queue. The new element is always inserted from the rear end.
● deQueue(): This function deletes an element from the Queue. The deletion in a Queue always takes place from the front end.
Q17) Write the application of a circular queue?
A17) Applications of Circular Queue
The circular Queue can be used in the following scenarios:
● Memory management: The circular queue provides memory management. As we have already seen in the linear queue, the memory is not managed very efficiently. But in case of a circular queue, the memory is managed efficiently by placing the elements in a location which is unused.
● CPU Scheduling: The operating system also uses the circular queue to insert the processes and then execute them.
● Traffic system: In a computer-control traffic system, traffic lights are one of the best examples of the circular queue. Each traffic light gets ON one by one after every interval of time. Like red light gets ON for one minute then yellow light for one minute and then green light. After the green light, the red light gets ON.
Q18) Explain Priority Queue?
A18) A priority queue is an abstract data type that behaves similarly to the normal queue except that each element has some priority, i.e., the element with the highest priority would come first in a priority queue. The priority of the elements in a priority queue will determine the order in which elements are removed from the priority queue.
The priority queue supports only comparable elements, which means that the elements are either arranged in an ascending or descending order.
For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a priority queue with an ordering imposed on the values from least to the greatest. Therefore, the 1 number would be having the highest priority while 22 will be having the lowest priority.
Characteristics of a Priority queue
A priority queue is an extension of a queue that contains the following characteristics:
● Every element in a priority queue has some priority associated with it.
● An element with the higher priority will be deleted before the deletion of the lesser priority.
● If two elements in a priority queue have the same priority, they will be arranged using the FIFO principle.
Let's understand the priority queue through an example.
We have a priority queue that contains the following values:
1, 3, 4, 8, 14, 22
All the values are arranged in ascending order. Now, we will observe how the priority queue will look after performing the following operations:
● poll(): This function will remove the highest priority element from the priority queue. In the above priority queue, the '1' element has the highest priority, so it will be removed from the priority queue.
● add(2): This function will insert the '2' element in a priority queue. As 2 is the smallest element among all the numbers so it will obtain the highest priority.
● poll(): It will remove the '2' element from the priority queue as it has the highest priority queue.
● add(5): It will insert 5 elements after 4 as 5 is larger than 4 and lesser than 8, so it will obtain the third highest priority in a priority queue.
Q19) What are the types of Priority Queues?
A19) There are two types of priority queue:
● Ascending order priority queue: In ascending order priority queue, a lower priority number is given as a higher priority in a priority. For example, we take the numbers from 1 to 5 arranged in an ascending order like 1,2,3,4,5; therefore, the smallest number, i.e., 1 is given as the highest priority in a priority queue.
● Descending order priority queue: In descending order priority queue, a higher priority number is given as a higher priority in a priority. For example, we take the numbers from 1 to 5 arranged in descending order like 5, 4, 3, 2, 1; therefore, the largest number, i.e., 5 is given as the highest priority in a priority queue.
Q20) Write the difference between stack and queue?
A20) Difference between Stack and Queue
Parameter | Stack Data Structure | Queue Data Structure |
Basics | It is a linear data structure. The objects are removed or inserted at the same end. | It is also a linear data structure. The objects are removed and inserted from two different ends. |
Working Principle | It follows the Last In, First Out (LIFO) principle. It means that the last inserted element gets deleted at first. | It follows the First In, First Out (FIFO) principle. It means that the first added element gets removed first from the list. |
Pointers | It has only one pointer- the top. This pointer indicates the address of the topmost element or the last inserted one of the stack. | It uses two pointers (in a simple queue) for reading and writing data from both the ends- the front and the rear. The rear one indicates the address of the last inserted element, whereas the front pointer indicates the address of the first inserted element in a queue. |
Operations | Stack uses push and pop as two of its operations. The pop operation functions to remove the element from the list, while the push operation functions to insert the element in a list. | Queue uses enqueue and dequeue as two of its operations. The dequeue operation deletes the elements from the queue, and the enqueue operation inserts the elements in a queue. |
Structure | Insertion and deletion of elements take place from one end only. It is called the top. | It uses two ends- front and rear. Insertion uses the rear end, and deletion uses the front end. |
Full Condition Examination | When top== max-1, it means that the stack is full. | When rear==max-1, it means that the queue is full. |
Empty Condition Examination | When top==-1, it indicates that the stack is empty. | When front = rear+1 or front== -1, it indicates that the queue is empty. |
Variants | A Stack data structure does not have any types. | A Queue data structure has three types- circular queue, priority queue, and double-ended queue. |
Visualization | You can visualize the Stack as a vertical collection. | You can visualize a Queue as a horizontal collection. |
Implementation | The implementation is simpler in a Stack. | The implementation is comparatively more complex in a Queue than a stack. |