Implement Stack using Queues in C++

C++Server Side ProgrammingProgramming

Suppose we want to implement one stack using a queue. We have to define these methods for the stack.

  • push(x) − Push x onto stack.

  • pop() − Delete and return top element from stack

  • top() − Return the top element from stack.

  • empty() − Return whether the stack is empty or not.

So, if we call the functions push(10), push(20), then call pop(), pop(), then the output will be 20, 10

To solve this, we will follow these steps −

  • Define one deque q

  • Define a function push(), this will take x,

  • insert x at the beginning of q

  • Define a function pop()

  • k := first element of q

  • delete front element from q

  • return k

  • Define a function top()

  • return first element of q

  • Define a function empty()

  • if q is empty, then −

    • return true

  • Otherwise

    • return false

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class MyStack {
private:
   deque<int> q;
public:
   void push(int x){
      q.push_front(x);
   }
   int pop(){
      int k = q.front();
      q.pop_front();
      return k;
   }
   int top(){
      return q.front();
   }
   bool empty(){
      if (q.empty())
         return true;
      else
         return false;
   }
};
main(){
   MyStack ob;
   ob.push(10);
   ob.push(20);
   cout << (ob.pop()) << endl;
   cout << (ob.pop()) << endl;
}

Input

push(10),push(20),pop(),pop()

Output

20
10
raja
Published on 10-Jun-2020 12:26:04
Advertisements