Implement a queue using two stacks. code example
Example 1: c++ stack and queue
using namespace std;
void printStack(stack<int> custstack)
{
for(int i = 0; i < 3; i++)
{
int y = custstack.top();
cout << y << endl;
custstack.pop();
}
}
void printQueue(queue<int> custqueue)
{
for(int i = 0; i < 3; i++)
{
int y = custqueue.front();
cout << y << endl;
custqueue.pop();
}
}
int main ()
{
cout << "Stack:" << endl;
// this stack stacks three elements one by one and displays each element before its removal
stack<int> MY_STACK; // define stack and initialize to 3 elements
MY_STACK.push(69); // last element popped / displayed
MY_STACK.push(68); // second element popped / displayed
MY_STACK.push(67); // third popped/displayed
printStack(MY_STACK);
cout << endl << "Switching to queue" << endl;
queue<int> MY_QUEUE;
MY_QUEUE.push(69); // first out
MY_QUEUE.push(68); // second out
MY_QUEUE.push(67); // third out
printQueue(MY_QUEUE);
return 0;
}
Example 2: python list as stack and queue
def isEmpty(stk):
if stk==[]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
print("Underflow")
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)
print("Popped item is "+str(item))
def Display(stk):
if isEmpty(stk):
print("Stack is empty")
else:
top=len(stk)-1
print("Elements in the stack are: ")
for i in range(top,-1,-1):
print (str(stk[i]))
if __name__ == "__main__":
stk=[]
top=None
Push(stk,1)
Push(stk,2)
Push(stk,3)
Push(stk,4)
Pop(stk)
Display(stk)