Implement a queue using two stacks.
Difficulty level
Video recording
This exercise is mostly suitable for students
typedef struct
{
stack L , R;
} queue;
queue CreateQueue()
{
queue q;
q.L = CreateStack();
q.R=CreateStack();
return q;
}
int isEmptyQueue(queue q)
{
return isEmptyStack(q.L);
}
int isFullQueue(queue q)
{
return isFullStack(q.L);
}
int EnQueue(queue *q, element e)
{
if(isFullQueue(*q)) return 0;
Push(&(q->L),e);
return 1;
}
int DeQueue(queue *q)
{
element e;
if(isEmptyQueue(*q)) return 0;
while(Top(q->L,&e))
{
Pop(&(q->L));
if(!isEmptyStack(q->L))
Push(&(q->R),e);
}
while(Top(q->R,&e) && Pop(&(q->R)) && Push(&(q->L),e ) );
return 1;
}
int Front(queue q, element *e)
{
if(isEmptyQueue(q)) return 0;
while(Top(q.L,e) && Pop(&(q.L)) ) ;
return 1;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Finding a value in an array using Interpolation search