数据结构实验之栈六:下一较大值(二)

来源:互联网 发布:武汉淘宝摄影 编辑:程序博客网 时间:2024/05/16 07:15
代码不是个人所写,所以比较乱。总体思路是每输入一个值,就入栈向上查找,记录上面元素的下一较大值
#include <stdio.h>#include <malloc.h>#include <iostream>#include <algorithm>using namespace std;#define STACKSIZE 110000struct node{    int data;    int id;    int nextdata;}a[110000];typedef struct{    struct node *top;    struct node *base;    int stacksize;} st;void initial(st &s){    s.base = (struct node *)malloc(sizeof(struct node)*STACKSIZE);    s.top = s.base;    s.stacksize = STACKSIZE;}void clean(st &s){    s.top = s.base;}void push(st &s, struct node e){    *s.top = e;    s.top++;}void pop(st &s, node &e){    if(s.base!=s.top)    {        s.top--;        e = *s.top;    }}int stackempty(st &s){    return s.top==s.base?1:0;}void gettop(st &s, node &e){    e = *(s.top-1);}int main(){    ios::sync_with_stdio(false);    st s;    initial(s);    int t;    while(~scanf("%d", &t))    {        while(t--)        {            clean(s);            int n;            scanf("%d", &n);            for(int j = 1; j<= n; j++)            {                scanf("%d", &a[j].data);                a[j].id = j;                a[j].nextdata = -1;                if(stackempty(s))                {                    push(s,a[j]);                }                else                {                    while(!stackempty(s))                    {                        node e;                        gettop(s,e);                        int k = e.id;                        if(e.data < a[j].data)                        {                            a[k].nextdata = a[j].data;                            pop(s,e);                        }                        else break;                    }                    push(s,a[j]);                }            }            for(int i = 1; i<= n; i++)                {                    printf("%d-->%d\n", a[i].data, a[i].nextdata);                }                if(t!=0)                    printf("\n");        }    }}

0 0