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
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);
}