From 267c042934f3f2a8c0b8b469c3daa333d4fa4b4d Mon Sep 17 00:00:00 2001 From: Sagar Satapathy Date: Tue, 9 Oct 2018 14:37:59 +0530 Subject: [PATCH] Added Reverse_Queue.cpp (#120) * Added Reverse_Queue.cpp * Update stack.hpp --- Data Structures/C:C++/Stack/Reverse_Queue.cpp | 48 +++++++++++++++++++ Data Structures/C:C++/Stack/stack.hpp | 2 +- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 Data Structures/C:C++/Stack/Reverse_Queue.cpp diff --git a/Data Structures/C:C++/Stack/Reverse_Queue.cpp b/Data Structures/C:C++/Stack/Reverse_Queue.cpp new file mode 100644 index 00000000..fbae88ad --- /dev/null +++ b/Data Structures/C:C++/Stack/Reverse_Queue.cpp @@ -0,0 +1,48 @@ +/* +An effective CPP program to reverse a Queue.In this program, +a Queue is populated with values and then it is reversed using the use of Stack. +Time Complexity:O(n) +Space Complexity:Extra Space for Stack +#include +*/ +using namespace std; +void Print(queue& Queue) +{ + while (!Queue.empty()) { + cout << Queue.front() << " "; + Queue.pop(); + } +} + +// Function to reverse the queue +void reverseQueue(queue& Queue) +{ + stack Stack; + while (!Queue.empty()) { + Stack.push(Queue.front()); + Queue.pop(); + } + while (!Stack.empty()) { + Queue.push(Stack.top()); + Stack.pop(); + } +} + +// Main Function +int main() +{ + queue Queue; + Queue.push(1); + Queue.push(2); + Queue.push(3); + Queue.push(4); + Queue.push(5); + Queue.push(6); + Queue.push(7); + Queue.push(8); + Queue.push(9); + Queue.push(10); + + reverseQueue(Queue); + Print(Queue); +} \ No newline at end of file diff --git a/Data Structures/C:C++/Stack/stack.hpp b/Data Structures/C:C++/Stack/stack.hpp index 9d885fd0..41277b1b 100644 --- a/Data Structures/C:C++/Stack/stack.hpp +++ b/Data Structures/C:C++/Stack/stack.hpp @@ -18,7 +18,7 @@ struct stackmp{ ll_node *new_node = create_node(new_data); ll_node *temp_node = this->top; new_node->next = temp_node; - this->top = new_node; + this->top = new_node; // here "this" pointer is used to access the current class's object's parameters size++; }