top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to reverse a stack using a queue?

+1 vote
411 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 Google+ Share Button LinkedIn Share Button Multiple Social 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
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...