top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to reverse a stack using a queue?

+1 vote
3,556 views

How to reverse a stack using a queue?
Preferably share the sample C code?

posted Jul 7, 2017 by Ajay Kumar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Its same as reversing the stack using the stack. Simply pop and put into the rear of the queue till last element. Now pick from the front of the queue and push into the stack and you are done.

See the following sample implementation which I found on the Internet -

#include<conio.h>
#include<stdio.h>

#define MAX 100

void show(int stack[],int size,int top)
{
    int i;
    for(i=0;i<size;i++)
    {
        printf("\nValue at %d is %d",top,stack[top]);
        top=top-1;
    }
}

void reverse(int stack[],int qu[],int *t,int *r,int *f)
{
    *f=0;
    while(*t>-1)
    {
        *r=*r+1;
        qu[*r]=stack[*t];
        *t=*t-1;
    }
    while(*f<=*r)
    {
        *t=*t+1;
        stack[*t]=qu[*f];
        *f=*f+1;
    }
}

void main()
{
    int size;
    int item,t,i,stack[MAX],quee[MAX];
    int top=-1,front=-1,rear=-1;

    printf("Enter size of stack::");
    scanf("%d",&size);

    for(i=0;i<size;i++)
    {
        top=top+1;
        printf("Enter value of for position %d ::",top);
        scanf("%d",&item);
        stack[top]=item;
    }

    show(stack,size,top);
    reverse(stack,quee,&top,&rear,&front);

    printf("\nAfter reverse..............");
    show(stack,size,top);

    getch();
}
answer Jul 8, 2017 by Salil Agrawal
...