关于用c建一个栈求下一个较大值

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int max_size = 100414;
struct Node{
    int x, id;
};
class stack{
private:
    int size;
    Node sta[max_size];
public:
    stack(){size = 0;}
    void push(Node x);
    Node top();
    void pop();
    bool empty();
};
void stack::push(Node x){
    sta[size++] = x;
}
Node stack::top(){
    return sta[size-1];
}
void stack::pop(){
    size--;
}
bool stack::empty(){
    return size == 0;
}
int rec[max_size];
int book[max_size];
int main(){
    int T, n, i;
    Node t1, t2;
    scanf("%d", &T);
    while(T--){
        stack s1;
        scanf("%d", &n);
        for(i = 1; i <= n; i++){
            scanf("%d", &rec[i]);
            t1.x = rec[i], t1.id = i;
            while(!s1.empty()){
                t2 = s1.top();
                if(t2.x < t1.x){
                    s1.pop();
                    book[t2.id] = t1.x;
                }
                else break;
            }
            s1.push(t1);
        }
        while(!s1.empty()){
            t2 = s1.top();
            s1.pop();
            book[t2.id] = -1;
        }
        for(i = 1; i <= n; i++){
            printf("%d-->%d\n", rec[i], book[i]);
        }
        if(T) printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/doge__/article/details/83210602