Skip to content

Instantly share code, notes, and snippets.

@shitu13
Last active May 17, 2024 18:05
Show Gist options
  • Save shitu13/832246efe51af7e57f6204f3971b4a2c to your computer and use it in GitHub Desktop.
Save shitu13/832246efe51af7e57f6204f3971b4a2c to your computer and use it in GitHub Desktop.
/////// 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);
}
};
@shitu13
Copy link
Author

shitu13 commented May 17, 2024

Find this problem on GeeksForGeeks. Problem Link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment