
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Implement Stack using Queues in C++
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 −
#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
- Related Articles
- C++ Program to Implement Stack Using Two Queues
- Python Program to Implement Stack Using Two Queues
- Using List as Stack and Queues in Python
- Python Program to Implement Queues using Stacks
- C++ Program to Implement Stack using array
- C++ Program to Implement Stack using linked list
- Python Program to Implement Stack using One Queue
- How can we Implement a Stack using Queue in Java?
- Python Program to Implement a Stack using Linked List
- How can we Implement a Queue using Stack in Java?\n
- IPC using Message Queues
- C++ Program to Implement Stack
- C++ Program to Implement Stack in STL
- Python Program to Implement a Stack
- Implement a stack from a LinkedList in Java
