DS Practical Slip 8 Q B

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)

  1. Use an array to represent the queue.
  2. Use front and rear pointers to track the queue elements.
  3. Accept n elements from the user and insert them into the queue.
  4. Reverse the queue:
    • Use two indices: start = front and end = rear.
    • Swap elements at start and end.
    • Increment start and decrement end until start < end.
  5. 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.

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top