From 8dec2fce88989ee55135c505fd9fa89f2caa85a2 Mon Sep 17 00:00:00 2001 From: RAJ VARDHAN CHAUDHARY <112545110+rajchaudhary99@users.noreply.github.com> Date: Sat, 7 Oct 2023 12:31:06 +0530 Subject: [PATCH] Create implementing a stack using two queues.cpp --- implementing a stack using two queues.cpp | 56 +++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 implementing a stack using two queues.cpp diff --git a/implementing a stack using two queues.cpp b/implementing a stack using two queues.cpp new file mode 100644 index 00000000..504768e9 --- /dev/null +++ b/implementing a stack using two queues.cpp @@ -0,0 +1,56 @@ +#include +#include + +using namespace std; + +class StackUsingQueues { +public: + void push(int x) { + q1.push(x); + } + + int pop() { + while (q1.size() > 1) { + q2.push(q1.front()); + q1.pop(); + } + int popped = q1.front(); + q1.pop(); + swap(q1, q2); + return popped; + } + + int top() { + while (q1.size() > 1) { + q2.push(q1.front()); + q1.pop(); + } + int topElement = q1.front(); + q2.push(topElement); + swap(q1, q2); + return topElement; + } + + bool empty() { + return q1.empty(); + } + +private: + queue q1, q2; +}; + +int main() { + StackUsingQueues stack; + + stack.push(1); + stack.push(2); + stack.push(3); + + cout << "Top element: " << stack.top() << endl; + cout << "Popped element: " << stack.pop() << endl; + + cout << "Top element: " << stack.top() << endl; + cout << "Is stack empty? " << (stack.empty() ? "Yes" : "No") << endl; + + return 0; +}