C Program to Reverse the Elements of a Queue (Static Implementation)
A Queue is a linear data structure that follows FIFO (First In First Out). In this program, we will use a static array to implement the queue and reverse its elements.
📝 Problem Statement
B) Write a program to reverse the elements of a queue (Use Static implementation of Queue).
đź’ˇ Logic (Simple Student-Friendly Steps)
- Use an array to represent the queue.
- Use
frontandrearpointers to track the queue elements. - Accept
nelements from the user and insert them into the queue. - Reverse the queue:
- Use two indices:
start = frontandend = rear. - Swap elements at
startandend. - Increment
startand decrementenduntilstart < end.
- Use two indices:
- Display the reversed queue.
đź’» Source Code (Static Queue Version)
#include <stdio.h>
#define MAX 100
int main()
{
int queue[MAX];
int front = 0, rear = -1;
int n, i, temp;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter elements:\n");
for(i = 0; i < n; i++)
{
rear++;
scanf("%d", &queue[rear]);
}
// Reverse the queue
int start = front;
int end = rear;
while(start < end)
{
temp = queue[start];
queue[start] = queue[end];
queue[end] = temp;
start++;
end--;
}
printf("Reversed queue is:\n");
for(i = front; i <= rear; i++)
printf("%d ", queue[i]);
return 0;
}
🖥️ Sample Output
Enter number of elements: 5
Enter elements:
10 20 30 40 50
Reversed queue is:
50 40 30 20 10
🎓 Viva Questions with Answers
1. What is a queue?
A queue is a linear data structure that follows FIFO (First In First Out).
2. What is static implementation of queue?
Queue is implemented using a fixed-size array.
3. What do front and rear indicate?
front→ index of the first element.rear→ index of the last element.
4. How do we reverse a queue?
By swapping elements from start to end using two pointers.
5. What is the time complexity of reversing a queue?
O(n), because each element is swapped at most once.
