#include<stdio.h>
typedef struct
{
int front,rear,arr[30];
}queue;
typedef struct
{
queue q;
}stack;
stack s;
void init()
{
s.q.front = s.q.rear = -1;
}
int isEmpty()
{
if(s.q.front==-1)
return 1;
return 0;
}
void enqueue(int element)
{
if(isEmpty())
s.q.front++;
s.q.arr[++s.q.rear] = element;
}
int dequeue()
{
int element = s.q.arr[s.q.front];
if(s.q.front==s.q.rear) //last element present
init();
else
s.q.front++;
return element;
}
int empty()
{
if(isEmpty())
return 1;
return 0;
}
void push(int element)
{
int i,j;
enqueue(element);
if(!empty())
{
j=s.q.rear;
for(i=s.q.front;i<j;i++)
{
dequeue(s.q.arr[i]);
enqueue(s.q.arr[i]);
}
}
}
int pop()
{
if(empty())
{
printf("\nStack is empty.Can't pop");
return -1;
}
else
return dequeue();
}
void display()
{
int i;
if(empty())
printf("\nStack is empty");
else
{
printf("\n");
for(i=s.q.front;i<=s.q.rear;i++)
printf("%d ",s.q.arr[i]);
}
}
int main()
{
int element;
init();
push(1);
display();
push(2);
display();
push(3);
display();
element = pop();
if(element!=-1)printf("\nPopped element = %d",element);
display();
return 0;
}
O/P
No comments:
Post a Comment