Page 150 - DCAP407_DATA_STRUCTURE
P. 150
Unit 8: Queues
2. A queue is created using an array named Q with an element capacity of 20. A
variable named COUNT is declared to store the count of number elements
present in the queue.
3. Four functions are created namely, Q_F(), Q_E(), rear_insert(),
front_delete(),and display(). The user has to select an appropriate function to
be performed.
4. The switch statement is used to call the rear_insert(), front_delete(), and
display() functions.
5. When the user enters 1, rear_insert() function is called. In the rear_insert()
function, the if loop checks if the count is full. If the condition is true, then
the program prints a message “Queue is empty”. Else, it checks for the value
of R and assigns the element (num) entered by the user to R. Initially, when
there are no elements in the queue, the value of R will be 0. After every
insertion, the variable COUNT is incremented.
6. When the user enters 2, the front_delete() function is called. In this function,
the if loop checks if the variable COUNT is empty. If the condition is true,
then the program prints a message “Queue underflow”. Else, the element in
the 0 position will be deleted. The size of F is computed and the COUNT is
th
set to 1.
7. When the user enters 3, the display() function is called. In this function, the if
loop checks if the value of COUNT is 0. If the condition is true, the program
prints a message “Queue is empty”. Else, the value of F is assigned to the
variable i. The for loop then displays the elements present in the queue.
8. When the user enters 4, the program terminates.
8.4.3 Priority Queue
In priority queue, the elements are inserted and deleted based on their priority. Each element is
assigned a priority and the element with the highest priority is given importance and processed first. If
all the elements present in the queue have the same priority, then the first element is given importance.
Program for Implementation of Priority Queue
#include<stdio.h>
#include<malloc.h>
struct queue
{
int PRI;
int value;
struct queue *next;
}*F, *q, *tmp, *new;
typedef struct queue *P;
void ins()
{
int num, el_pri;
new = ( P ) malloc(10 );
printf( "Enter the element to be inserted:" );
scanf( "%d", &num );
printf( "Enter a priority:" );
scanf( "%d", &el_pri );
new->value = num;
new->PRI = el_pri;
LOVELY PROFESSIONAL UNIVERSITY 143