此C ++堆栈实现不会产生任何输出

问题描述 投票:0回答:1
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";
    }
  }
}

这里n是数组a[]的大小。在控制台上不会产生任何输出。

示例输入:a[] = {3, 1, 2}

示例预期输出:

3
2 1
c++ data-structures stack implementation
1个回答
0
投票
  • 您访问了s.top()时没有检查s处的if (a[i] < s.top()) {是否为空,并导致分段错误。
  • 额外的换行符在后面的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()){
            while(!s.empty()){
                cout << s.top() <<" ";
                s.pop();
            }
            cout << "\n";
        }
        s.push(a[i]); 
    }
    while(!s.empty()){
        cout << s.top() <<" ";
        s.pop();
    }
    cout << "\n";
}

或此:

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.