Last active
May 17, 2024 18:05
-
-
Save shitu13/832246efe51af7e57f6204f3971b4a2c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/////// Approach 1: Space Complexity: O(n) | |
class Solution{ | |
public: | |
void Reverse(stack<int> &St){ | |
if(St.empty()){ | |
return; | |
} | |
int top = St.top(); | |
St.pop(); | |
Reverse(St); | |
stack<int> temp; | |
while(!St.empty()){ | |
temp.push(St.top()); | |
St.pop(); | |
} | |
St.push(top); | |
while(!temp.empty()){ | |
St.push(temp.top()); | |
temp.pop(); | |
} | |
} | |
}; | |
/////// Approach 2: Space Complexity: O(1) | |
class Solution{ | |
private: | |
void insertAtBottom(stack<int> &St, int ele){ | |
if(St.empty()){ | |
St.push(ele); | |
return; | |
} | |
int top = St.top(); | |
St.pop(); | |
insertAtBottom(St, ele); | |
St.push(top); | |
} | |
public: | |
void Reverse(stack<int> &St){ | |
if(St.empty()){ | |
return; | |
} | |
int top = St.top(); | |
St.pop(); | |
Reverse(St); | |
insertAtBottom(St, top); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Find this problem on GeeksForGeeks. Problem Link