Question:
Exercise 6:
Stack to Queue Creation
Write a program that creates a Queue from a stack. After creation the top of the stack will be the front of the queue.
Input Data Output Data
S: 1 2 3 4 5 Q: 5 4 3 2 1
Soultion:
#include <stdio.h>
#include <stdlib.h>
#include<process.h>
#include<limits.h>
#define SIZE 100
#define MAX 100
int top = -1, stack[MAX], queue[MAX];
//int stack[MAX];
int front = 0;
int rear = 0;
void push();
void pop();
void displayStack();
void enqueue(int item)
{
if(rear == MAX)
{
printf("Queue is Full!!!\n");
}
else if (front == 0)
{
queue[rear] = item;
rear = rear + 1;
}
}
void stackToQueue(){
for (int i=top; i>=0; --i)
{
enqueue(stack[i]);
}
}
void displayQueue()
{
if (front == rear)
{
printf("\nQueue is empty!!!");
}
else
{
printf("Items in Queue...\n\n");
for (int i=front; i<rear; i++)
{
printf("%d ", queue[i]);
}
printf("\n");
}
}
int main()
{
printf("Total number: ");
int n, i;
scanf("%d",&n);
for(i=0; i<n; i++)
push();
stackToQueue();
displayQueue();
//displayStack();
}
void push()
{
int data;
if(top == MAX-1)
{
printf("\nStack is full!!!");
}
else
{
scanf("%d", &data);
top = top + 1;
stack[top] = data;
}
}
void pop()
{
if (top == -1)
{
printf("\nStack is empty!!!");
}
else
{
printf("\nDeleted element is %d", stack[top]);
top = top - 1;
}
}
void displayStack()
{
if(top == -1)
{
printf("\nStack is empty!!!");
}
else
{
printf("\nStack is : \n");
for (int i=top; i>=0; --i)
{
printf("%d\n", stack[i]);
}
}
}