Showing posts with label hacker rank solution in c. Show all posts
Showing posts with label hacker rank solution in c. Show all posts

Wednesday, 15 March 2017

implementing queue using two stacks

THE BELOW PROGRAM FAILS IN FEW TEST CASES

#include<stdio.h>
int front_val,s1[100],s2[100],top1=-1,top2=-1;
void enqueue(int x) {
int t;
    while(top2 != -1)
    {
     t=s2[top2--];
     s1[++top1]=t;
    }
if(top1==-1) {
        front_val = x;
    }
    s1[++top1]=x;
}

int dequeue() {
int t,x;
    while(top1 != -1) {
    t=s1[top1--];
    s2[++top2]=t;
    }
     x = s2[top2--];
 
    if(top2 != -1) {
        front_val = s2[top2];
    }
    return x;
}

int peek() {
    return front_val;
}

main()
{
int t,i,opt,val;
    scanf("%d", &t);
    for(i=0;i<t;i++)
{
        scanf("%d", &opt);
        switch(opt)
{
            case 1:
                scanf("%d", &val);
                enqueue(val);
                break;
            case 2:
                dequeue();
                break;
            case 3:
                printf("%d\n", peek());
                break;
        }
}
}