DS Practical Slip 2 Q B

C Program to Reverse the Elements of a Queue (Static Implementation)

Queue is a linear data structure that follows FIFO (First In First Out) principle. In this program, we will use a static array implementation of 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. Declare a queue using an array.
  2. Use two variables:
    • front
    • rear
  3. Insert elements into the queue.
  4. To reverse the queue:
    • Use two variables (i and j).
    • Swap elements from front to rear.
    • Continue until i < j.
  5. Print the reversed queue.

👉 Reversing is done using swapping:

temp = queue[i];
queue[i] = queue[j];
queue[j] = temp;

💻 Source Code (Simple Static Queue Version)

#include <stdio.h>

#define MAX 100

int queue[MAX];
int front = 0, rear = -1;

int main()
{
    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?

It means implementing queue using a fixed-size array.

3. What are front and rear?

  • front points to the first element.
  • rear points to the last element.

4. What is the time complexity of reversing the queue?

O(n), because we swap elements once.

5. What is overflow in queue?

Overflow occurs when we try to insert elements beyond the maximum size.

Spread the love

Leave a Comment

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

Scroll to Top