0

Hi I am trying to find the number of previous towers less than or equal to the current one , this solution is working great for inputs(NumOfTowers) <=10, but for the NumOfTowers >10 the code is going in segfault, i could not see the issue here,

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

int main()
{
    std::stack<int> Towers;    //for storing the Height of the towers
    std::stack<int> TempTowers; // Temrory buffer stack
    std::stack<int> CountTowers; //for storing the count of all previous  
                                   towers less than the current one
    unsigned int NumTestCases,NumOfTowers,i,j,count=1,temp,temp_height;
    cin>>NumTestCases;
    cin>>NumOfTowers;


    while(NumTestCases){

        while(!Towers.empty()){
            Towers.pop();
        }
       for(i=0;i<NumOfTowers;i++){
           cin>>temp;
           Towers.push(temp);
       }
       for(i=0;i<NumOfTowers-1;i++){
           count=1;
           temp_height=Towers.top();
           Towers.pop();
           temp=Towers.top();

           while(temp<temp_height){
               count++;
               TempTowers.push(temp);
               Towers.pop();
               temp=Towers.top();
           }

            CountTowers.push(count);

            while(!TempTowers.empty()){
                temp=TempTowers.top();
                TempTowers.pop();
                Towers.push(temp);
           }

       }       
       NumTestCases--;
       cout<<"1"<<" ";
       while(!CountTowers.empty()){
           cout<<CountTowers.top()<<" ";
           CountTowers.pop();
       }
       cout<<"\n";
    }

}

any help would be great.

user2910111
  • 342
  • 2
  • 3
  • 11
  • [`using namespace std;` is a bad practice](https://stackoverflow.com/q/1452721/2176813), never use it. – tambre Oct 23 '17 at 07:33
  • Please list the input and the desired output, otherwise the question is off-topic, as we aren't telephatic and can't figure out what you want the program to do. – tambre Oct 23 '17 at 07:33
  • Use a debugger. –  Oct 23 '17 at 07:39

2 Answers2

1

Change this

while(temp<temp_height){
               count++;
               TempTowers.push(temp);
               Towers.pop();      // Popped the last element
               temp=Towers.top(); // no more elements left
           }

to this

while(!Towers.empty() && Towers.top() < temp_height)
{
  ++count;
  TempTowers.push(Towers.top());
  Towers.pop();
}

The issue wasn't with the length of the input but the order of it. If I/p = {1, 2, 3, 4} your code would give a error when it tried to access top() of a empty stack.

thebenman
  • 1,621
  • 14
  • 35
0

You are calling temp=Towers.top(); on an empty stack, here

    while(temp<temp_height){        
       count++;
       TempTowers.push(temp);
       Towers.pop();
       temp=Towers.top();
    }

Change this line to the follwing two lines:

    if (Towers.size() > 0) temp = Towers.top();
    else break;