技巧:预先将-1压入栈中
C++ 代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int stk[N], tt = 0, n;
int main() {
cin >> n;
stk[++tt] = -1;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
while (a <= stk[tt]) tt--;
cout << stk[tt] << " ";
stk[++tt] = a;
}
return 0;
}