Question

write a function to insert an element in the middle of a queue. Please use C++...

write a function to insert an element in the middle of a queue. Please use C++ and make sure its a function. Thanks

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <stdio.h>

#define MAX 100
void enqueue(int a);
void insert_middle(int a); // insert the lement into the middle function
void display();
int queue[MAX];
int rear = -1;
int front = -1;

int main()
{
enqueue(1);
enqueue(2);
enqueue(3);
enqueue(4);
printf("Before inserting the element 5 into the middle : \n");
display();
insert_middle(5);
printf("After inserting the element 5 into the middle : \n");
display();
}

void enqueue(int a)
{
if(rear == MAX - 1)
{
printf("overflow"); // if it reaches to the maximm limit
}
else
{
if(front == - 1)
{
front = 0;
}
rear++;
queue[rear] = a;
}
}

void insert_middle(int a) // function for inserting the lement into the middle of the queue
{
int i;
for(i = rear; i >= (rear + 1) / 2; i--) // move the element for the second half to the consecutive locations
{
queue[i + 1] = queue[i];
}
queue[(rear + 1) / 2] = a; // place the value into the middle
rear++;
}

void display()
{
for(int i = front; i <= rear; i++) // displaying the elements in the queue format
{
printf("%d ", queue[i]);
}
printf("\n");
}

OUTPUT :

Before inserting the element 5 into the middle : 1 2 3 4 After inserting the element 5 into the middle : 1 2 5 3 4 ... Progra

Add a comment
Know the answer?
Add Answer to:
write a function to insert an element in the middle of a queue. Please use C++...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT