why am i getting wrong Answer?
Reverse Stack Doubt
@dare_devil_007, at line 6 , it should be for(int i=0;i<n;i++){ instead of
for(int i=0;i<n-i-1;i++){
ok thanks but if i am not using function to transfer then i am getting WA why?
#include<bits/stdc++.h>
using namespace std;
void reverseStack(stack&s1){
//helper stack
stack<int>s2;
int n = s1.size();
for(int i=0;i<n;i++){
int x = s1.top();
s1.pop();
//move n-i-1 elements from s1 to s2
for(int i=0;i<n-i-1;i++){
s2.push(s1.top());
s1.pop();
}
// put the element x in the s1;
s1.push(x);
// now move all the elements from s2 to s1
for(int i=0;i<n-i-1;i++){
s1.push(s2.top());
s2.pop();
}
}
}
int main() {
stack s;
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
s.push(x);
}
reverseStack(s);
while(!s.empty()){
cout<<s.top()<<" ";
s.pop();
}
return 0;
}
try to change the variable name for i to j
1 Like
sorry bro, that was so silly of me, iwas just checking for logic and neglected the variables