Skip to content

Commit

Permalink
Added Reverse_Queue.cpp (#120)
Browse files Browse the repository at this point in the history
* Added Reverse_Queue.cpp

* Update stack.hpp
  • Loading branch information
sagarbaba authored and srbcheema1 committed Oct 9, 2018
1 parent de7f276 commit 267c042
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
48 changes: 48 additions & 0 deletions Data Structures/C:C++/Stack/Reverse_Queue.cpp
Original file line number Diff line number Diff line change
@@ -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 <bits/stdc++.h>
*/
using namespace std;
void Print(queue<int>& Queue)
{
while (!Queue.empty()) {
cout << Queue.front() << " ";
Queue.pop();
}
}

// Function to reverse the queue
void reverseQueue(queue<int>& Queue)
{
stack<int> Stack;
while (!Queue.empty()) {
Stack.push(Queue.front());
Queue.pop();
}
while (!Stack.empty()) {
Queue.push(Stack.top());
Stack.pop();
}
}

// Main Function
int main()
{
queue<int> 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);
}
2 changes: 1 addition & 1 deletion Data Structures/C:C++/Stack/stack.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ struct stackmp{
ll_node<T> *new_node = create_node(new_data);
ll_node<T> *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++;
}

Expand Down

0 comments on commit 267c042

Please sign in to comment.