
stack me operation
C++ Code #include <stack> using namespace std ; void insert ( stack < int >& st , int x ){ if ( st . empty () || st . top () <= x ){ st . push ( x ); return ; } int temp = st . top (); st . pop (); insert ( st , x ); st . push ( temp ); } void sortStack ( stack < int >& st ){ if ( st . empty ()) return ; int x = st . top (); st . pop (); sortStack ( st ); insert ( st , x ); } Idea in Simple Words Remove the top element . Sort the remaining stack recursively . Insert the removed element in the correct position . Example Initial stack (top → bottom) 3 1 4 2 Sorted stack 4 3 2 1 (bottom → top → 1 2 3 4 ) Complexity Time: O(n²) Space: O(n) recursion stack 1. Reverse a Stack using Recursion Idea Pop the top element. Reverse the remaining stack. Insert the popped element at the bottom . Code (C++) #include <stack> using namespace std ; void insertBottom ( stack < int >& st , int x ){ if ( st . empty ()){ st . push ( x ); return ; } int temp = st . top (); st . pop (); insertBottom ( st , x )
Continue reading on Dev.to Beginners
Opens in a new tab




