Reverse a stack using temp memory and using recursion
Here is the code :
Thanks
#include <iostream> #include <conio.h> #include <stack> using namespace std; void reverse_stack1(stack<int> &s) { stack<int> temp; while (!s.empty()) { temp.push(s.top()); s.pop(); } s = temp; } void insertAtBottom(stack<int> &s, int val) { if (s.empty()) { s.push(val); } else { int temp = s.top(); s.pop(); insertAtBottom(s, val); s.push(temp); } } void reverse_stack2(stack<int> &s) { if (!s.empty()) { int temp = s.top(); s.pop(); reverse_stack2(s); insertAtBottom(s, temp); } } void print_stack(stack<int> s) { while (!s.empty()) { cout << s.top() << " "; s.pop(); } } void main() { stack<int> s_int; for (int i = 0; i <= 10; ++i) { s_int.push(i); } cout << "Before sorting " << endl; print_stack(s_int); stack<int> s = s_int; cout << endl << endl; cout << "After sorting (using reverse_stack2)" << endl; reverse_stack2(s_int); print_stack(s_int); cout << endl << endl; cout << "After sorting (using reverse_stack1)" << endl; reverse_stack1(s); print_stack(s); _getch(); }
Thanks
Comments
Post a Comment