首页 > 解决方案 > 此 C++ 堆栈实现不产生任何输出

问题描述

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-structuresstackimplementation

解决方案


  • 您访问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);
}

推荐阅读