Here is an algorithm to implement queue with two stacks:
stack stk1, stk2;
void push(element e)
{
push e in stk1;
}
element pop()
{
if(!stk2.empty()) {
return stk2[top_stk2--];
} else {
while(!stk1.empty())
{
stk2.push(stk1.pop());
}
return stk2[top_stk2];
}
}
stack stk1, stk2;
void push(element e)
{
push e in stk1;
}
element pop()
{
if(!stk2.empty()) {
return stk2[top_stk2--];
} else {
while(!stk1.empty())
{
stk2.push(stk1.pop());
}
return stk2[top_stk2];
}
}
Comments
Post a Comment
https://gengwg.blogspot.com/