0
void solve(int n, int a[]) {
  stack<int> s;
  s.push(a[0]);
  for (int i = 1; i < n; i++) {
    if (a[i] < s.top()) {
      while (!s.empty()) {
        cout << s.top() << " ";
        s.pop();
      }
      cout << "\n";
    } else {
      s.push(a[i]);
      cout << "\n";
    }
  }
}

Here n is the size of array a[]. It doesn't produce any output on console.

example input: a[] = {3, 1, 2}

example expected output:

3
2 1
MikeCAT
  • 73,922
  • 11
  • 45
  • 70

1 Answers1

0
  • You accessed s.top() without checking if s is empty at if (a[i] < s.top()) { and it is causing Segmentation Fault.
  • Extra newlines are printed at the latter cout << "\n";.
  • Values that are smaller than previous values are dropped.
  • Last chunk of input won't be printed.

Try this:

void solve(int n , int a[]){
    stack<int> s; 
    s.push(a[0]);  
    for(int i=1;i<n;i++){
        if(!s.empty() && a[i] < s.top()){
            while(!s.empty()){
                cout << s.top() <<" ";
                s.pop();
            }
            cout << "\n";
        }
        s.push(a[i]); 
    }
    while(!s.empty()){
        cout << s.top() <<" ";
        s.pop();
    }
    cout << "\n";
}

Or this:

void flush_stack(stack<int>& s) {
    while(!s.empty()){
        cout << s.top() <<" ";
        s.pop();
    }
    cout << "\n";
}

void solve(int n , int a[]){
    stack<int> s; 
    s.push(a[0]);  
    for(int i=1;i<n;i++){
        if(!s.empty() && a[i] < s.top()){
           flush_stack(s);
        }
        s.push(a[i]); 
    }
    flush_stack(s);
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70