Home > database >  insert element at bottom of stack
insert element at bottom of stack

Time:06-24

I am doing the Insert at Bottom of the stack question. This code is perfectly working in the CodeStudio but it is not giving the correct expected output in Visual studio code. why it is not displaying all the elements of the stack

# include <iostream>
# include <stack>
# include <vector>
# include <string>
using namespace std;

void Helper(stack<int>& myStack, int x){

    if(myStack.empty()){
      myStack.push(x);
      return ;
    }
    int temp=myStack.top();
    myStack.pop();
    Helper(myStack, x);
    myStack.push(temp);
 

}

stack<int> pushAtBottom(stack<int>& myStack, int x) 
{
     Helper(myStack,x);
    return myStack;
}

int main(){
 stack<int> s,ans;
 int n,a;
 cout<<"How many element : ";
 cin>>n;
 for(int i=0; i<n; i  ){
    cin>>a;
    s.push(a);
 }
  cout<<"New element : ";
 cin>>a;


 ans=pushAtBottom(s,a);
  cout<<"After inserting : ";
  for(int i=0; i<ans.size(); i  ){

    cout<<ans.top()<<" ";
    ans.pop();
 }
 cout<<endl;
 return 0;

}

Input

6

1 2 3 4 5

Expected Output

5 4 3 2 1 6

Output

After inserting : 5 4 3 

CodePudding user response:

The problem is how you print the elements:

for(int i=0; i<ans.size(); i  ){
    cout<<ans.top()<<" ";
    ans.pop();
}

Due to calling ans.pop() ans.size() will decrease by one every iteration. At the same time i will increase by one every iteration. Basically you iterate twice as fast as intended.

A better loop would be this:

while(ans.size() > 0) {
    cout << ans.top() << " ";
    ans.pop();
}  
  • Related