Unit – 2
Stacks and Queues
Q1) Write short notes on stacks?
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.
Q2) Describe Abstract Data Type?
A2) The abstract data type is a special kind of datatype, whose behavior is defined by a set of values and set of operations. The keyword “Abstract” is used as we can use these data types to perform different operations. But how those operations are working is totally hidden from the user. The ADT is made of primitive data types, but operation logics are hidden.
Here we will see the stack ADT. These are a few operations or functions of the Stack ADT.
● isFull(), This is used to check whether stack is full or not
● isEmpty(), This is used to check whether stack is empty or not
● push(x), This is used to push x into the stack
● pop(), This is used to delete one element from top of the stack
● peek(), This is used to get the top most element of the stack
● size(), this function is used to get number of elements present into the stack
Example
#include<iostream>
#include<stack>
Using namespace std;
Main(){
Stack<int> stk;
If(stk.empty()){
Cout << "Stack is empty" << endl;
} else {
Cout << "Stack is not empty" << endl;
}
//insert elements into stack
Stk.push(10);
Stk.push(20);
Stk.push(30);
Stk.push(40);
Stk.push(50);
Cout << "Size of the stack: " << stk.size() << endl;
//pop and display elements
While(!stk.empty()){
Int item = stk.top(); // same as peek operation
Stk.pop();
Cout << item << " ";
}
}
Output
Stack is empty
Size of the stack: 5
50 40 30 20 10
Q3) What do you mean by push operation?
A3) 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 1 – Push Operation Example
Q4) Write about pop operation?
A4) 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 2 – Pop Operation example
Q5) How to Array representation of stack in c?
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 in C language
Void push (int val,int n) //n is size of the stack
{
If (top == n )
Printf("\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 in C language
Int pop ()
{
If(top == -1)
{
Printf("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 in C language
Int peek()
{
If (top == -1)
{
Printf("Underflow");
Return 0;
}
Else
{
Return stack [top];
}
}
Q6) What is a linked list implementation of stack in c?
A6) 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 3: 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.
2. 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.
3. 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.
C Implementation
Void push ()
{
Int val;
Struct node *ptr =(struct node*)malloc(sizeof(struct node));
If(ptr == NULL)
{
Printf("not able to push the element");
}
Else
{
Printf("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;
}
Printf("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.
2. 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.
C Implementation
Void pop()
{
Int item;
Struct node *ptr;
If (head == NULL)
{
Printf("Underflow");
}
Else
{
Item = head->val;
Ptr = head;
Head = head->next;
Free(ptr);
Printf("Item popped");
}
}
Q7) Write the application of stacks?
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) Explain prefix and postfix expression?
A8) If we wish to execute a computation, frame a condition, or do anything else in a programming language, we employ a set of symbols to do it. An expression is made up of these symbols.
The following is an example of a phrase...
A value is represented by an expression, which is made up of operators and operands.
An operator, as defined above, is a symbol that performs a certain task, such as an arithmetic operation, a logical operation, or a conditional operation.
The operands are the values that the operators can use to complete the task. The operand can be a direct value, a variable, or a memory address.
Postfix expression
The operator is used after the operands in a postfix expression. "Operator follows the Operands," as the saying goes.
The following is the general structure of a Postfix expression...
Operand1 Operand2 Operator
Example
Prefix expression
Operator comes before operands in a prefix expression. "Operands follow the Operator," as the saying goes.
The following is the general structure of a Prefix expression...
Operator Operand1 Operand2
Example
Q9) Evaluated postfix expression?
A9) The compiler prefers to evaluate an expression in its postfix form in Infix To Postfix Conversion Using Stack. The advantages of the postfix form include the deletion of parentheses, which indicate evaluation priority, as well as the elimination of the requirement to follow hierarchy, precedence, and associativity rules when evaluating the expression.
Because Postfix expressions have no parenthesis and may be evaluated as two operands and an operator at a time, the compiler and computer can handle them more easily.
A Postfix Expression's evaluation rule is as follows:
- While reading the expression from left to right, push the element in the stack if it is an operand.
- Pop the two operands from the stack, if the element is an operator and then evaluate it.
- Push back the result of the evaluation. Repeat it till the end of the expression.
Algorithm
1) Add ) to postfix expression.
2) Read postfix expression Left to Right until ) encountered
3) If operand is encountered, push it onto Stack
[End If]
4) If operator is encountered, Pop two elements
i) A -> Top element
Ii) B-> Next to Top element
Iii) Evaluate B operator A
Push B operator A onto Stack
5) Set result = pop
6) END
Example
Expression: 456*+
Result: 34
Q10) What is the principle of recursion?
A10) 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
Q11) Define tail recursion?
A11) The recursive function is used as the function's last statement in the tail recursion. Tail recursion occurs when there is nothing left to do after returning from a recursive call. One example of tail recursion will be shown.
Example
#include <iostream>
Using namespace std;
Void printN(int n){
If(n < 0){
Return;
}
Cout << n << " ";
PrintN(n - 1);
}
Int main() {
PrintN(10);
}
Output
10 9 8 7 6 5 4 3 2 1 0
Non-tail recursion is preferable to tail recursion. Because there is no job remaining after the recursive call, the compiler will have an easier time optimizing the code. When a function is called, the address of that function is saved in the stack. So, if it's a tail recursion, there's no need to save addresses in the stack.
Recursion can be used to use factorials, however the function is not tail recursive. The fact(n-1) value is utilized within the fact (n).
Long fact(int n){
If(n <= 1)
Return 1;
n * fact(n-1);
}
We can make it tail recursive, by adding some other parameters. This is like below −
Long fact(long n, long a){
If(n == 0)
Return a;
Return fact(n-1, a*n);
}
Q12) How to remove recursion?
A12) A recursive function is one that calls itself (in the function body) over and over again. As long as the condition is met, this function will call itself.
There are two approaches to get rid of the recursion:
● Through Iteration
● Through Stack
Removal of recursion through iteration
A simple program of factorial through recursion
#include<stdio.h>
Main()
{
Int n, value;
Printf(“Enter the number”);
Scanf(“%d”,&n);
If(n<0)
Printf(“No factorial of negative number”);
Else
If(n==0)
Printf(“Factorial of zero is 1”);
Else
{
Value=factorial(n); /*function for factorial of number*/
Printf(“Factorial of %d= %d”,n,value);
}
}
Factorial (int k)
{
Int fact=1;
Ifk>1)
Fact=k*factorial(k-1); /*recursive function call*/
Return (fact);
Removal through stack
Let's pretend that P is a recursive procedure. The following is how recursive procedure P is transformed into a non-recursive procedure:
To begin, one must create: 1. A stack STPAR for each parameter PAR.
2. Each local variable VAR has its own stack STVAR.
3. A return address stack STADD and a local variable ADD
Following is the algorithm for converting the recursive procedure P to a non-recursive procedure. It is divided into three sections:
1. Preparation
2. Translating each recursive call P in procedure P.
3. Translating each return in procedure P.
- Preparation
(a) For each parameter PAR, create a stack STPAR, a stack STVAR for each local variable VAR, and a local variable ADD and a stack STADD to hold the return address.
(b) Make TOP NULL.
2. Translation of “step K.call P.”
(a) Push the current values of the parameters and local variable to the proper stacks, and STADD with the new return address [step ] K+1.
(b) Using the new argument values, reset the parameters.
(c) return to the first step. [Procedure P's first step]
3. Translation of “Step J.return”
(a) Return if STADD is not empty. [Control is transferred back to the main application].
(b) Restore the stacks' top values.
That is, set the top values on the stacks for the parameters and local variables, and the top value on the STADD for ADD.
(c) Go to the ADD step.
4. Return to Step L.
Q13) What is the difference between recursion and iteration?
A13) Recursion
- Selection structure is used in recursion.
- If the recursion step does not reduce the problem in a way that converges on some condition (base case), infinite recursion occurs, and infinite recursion might cause the system to fail.
- When a base case is found, the recursion ends.
- Due to the overhead of maintaining the stack, recursion is frequently slower than iteration.
- Iteration utilizes less memory than recursion.
- Recursion reduces the size of the code.
Example
Public class RecursionExample {
Public static void main(String args[]) {
RecursionExample re = new RecursionExample();
Int result = re.factorial(4);
System.out.println("Result:" + result);
}
Public int factorial(int n) {
If (n==0) {
Return 1;
}
Else {
Return n*factorial(n-1);
}
}
}
Result - 24
Iteration
- Iteration employs a structure of repetition.
- Iteration creates an infinite loop if the loop condition test never fails, and unlimited looping consumes CPU cycles repeatedly.
- When the loop condition fails, the iteration ends.
- Iteration is faster than recursion since it does not use the stack.
- It takes up less memory to iterate.
- Iteration lengthens the code.
Example
Public class IterationExample {
Public static void main(String args[]) {
For(int i = 1; i <= 5; i++) {
System.out.println(i + " ");
}
}
}
Output
1
2
3
4
5
Comparison table
Recursion | Iteration |
It makes use of Stack. | It doesn't make use of Stack. |
A Single Line Of Code | A Long Line of Code |
Iteration can be used to address the not-all-recursive problem. | Any iterative issue is recursively solved. |
Each step of recursion replicates itself on a lesser scale, until all of them are merged to solve the problem. | Iteration ensures that each step, like stepping stones across a river, clearly leads to the next. |
Recursion is the equivalent of heaping all of those steps on top of one another and then squashing them all into the answer. | Iteration is the process of converting a problem into a series of stages that are completed one by one. |
Performance is slow. | Performance that is quick. |
Q14) Define operation on queue?
A14) 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 4: 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.
Q15) Write about circular queue?
A15) 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 5 – 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.
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.
Q16) How to array implement a queue in c?
A16) 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
C function
Void insert (int queue[], int max, int front, int rear, int item)
{
If (rear + 1 == max)
{
Printf("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
C function
Int delete (int queue[], int max, int front, int rear)
{
Int y;
If (front == -1 || front > rear)
{
Printf("underflow");
}
Else
{
y = queue[front];
If(front == rear)
{
Front = rear = -1;
Else
Front = front + 1;
}
Return y;
}
}
Q17) Implement linked list of queues in c?
A17) 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
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
C function
Void insert(struct node *ptr, int item; )
{
Ptr = (struct node *) malloc (sizeof(struct node));
If(ptr == NULL)
{
Printf("\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;
}
}
}
Deletion
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
C function
Void delete (struct node *ptr)
{
If(front == NULL)
{
Printf("\nUNDERFLOW\n");
Return;
}
Else
{
Ptr = front;
Front = front -> next;
Free(ptr);
}
}
Q18) Explain dequeue?
A18) The dequeue stands for Double Ended Queue. In the queue, the insertion takes place from one end while the deletion takes place from another end. The end at which the insertion occurs is known as the rear end whereas the end at which the deletion occurs is known as the front end.
Fig 10: dequeue
Deque is a linear data structure in which the insertion and deletion operations are performed from both ends. We can say that deque is a generalized version of the queue.
Let's look at some properties of deque
● Deque can be used both as stack and queue as it allows the insertion and deletion operations on both ends.
● In deque, the insertion and deletion operation can be performed from one side. The stack follows the LIFO rule in which both the insertion and deletion can be performed only from one end; therefore, we conclude that deque can be considered as a stack.
● In deque, the insertion can be performed on one end, and the deletion can be done on another end. The queue follows the FIFO rule in which the element is inserted on one end and deleted from another end. Therefore, we conclude that the deque can also be considered as the queue.
There are two types of Queues, Input-restricted queue, and output-restricted queue.
- Input-restricted queue: The input-restricted queue means that some restrictions are applied to the insertion. In input-restricted queue, the insertion is applied to one end while the deletion is applied from both the ends.
2. Output-restricted queue: The output-restricted queue means that some restrictions are applied to the deletion operation. In an output-restricted queue, the deletion can be applied only from one end, whereas the insertion is possible from both ends.
Operations on Deque
The following are the operations applied on deque:
● Insert at front
● Delete from end
● insert at rear
● delete from rear
Other than insertion and deletion, we can also perform peek operation in deque. Through peek operation, we can get the front and the rear element of the dequeue.
We can perform two more operations on dequeue:
● isFull(): This function returns a true value if the stack is full; otherwise, it returns a false value.
● isEmpty(): This function returns a true value if the stack is empty; otherwise it returns a false value.
Q19) Define priority queue?
A19) 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.
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.
Types of Priority Queue
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.
Representation of priority queue
Now, we will see how to represent the priority queue through a one-way list.
We will create the priority queue by using the list given below in which INFO list contains the data elements, PRN list contains the priority numbers of each data element available in the INFO list, and LINK basically contains the address of the next node.
Let's create the priority queue step by step.
In the case of priority queue, lower priority number is considered the higher priority, i.e., lower priority number = higher priority.
Step 1: In the list, lower priority number is 1, whose data value is 333, so it will be inserted in the list as shown in the below diagram:
Step 2: After inserting 333, priority number 2 is having a higher priority, and data values associated with this priority are 222 and 111. So, this data will be inserted based on the FIFO principle; therefore 222 will be added first and then 111.
Step 3: After inserting the elements of priority 2, the next higher priority number is 4 and data elements associated with 4 priority numbers are 444, 555, 777. In this case, elements would be inserted based on the FIFO principle; therefore, 444 will be added first, then 555, and then 777.
Step 4: After inserting the elements of priority 4, the next higher priority number is 5, and the value associated with priority 5 is 666, so it will be inserted at the end of the queue.
Implementation of Priority Queue
The priority queue can be implemented in four ways that include arrays, linked list, heap data structure and binary search tree. The heap data structure is the most efficient way of implementing the priority queue, so we will implement the priority queue using a heap data structure in this topic. Now, first we understand the reason why heap is the most efficient way among all the other data structures.
Q20) Write the characteristics of priority queue?
A20) 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.