逆波兰式求值(用链栈求解)

如:求(22+3)*4=100

             输入 :22(空格)3+4*(回车)

             输出:100

#include
#include
#define maxsize 30
typedef struct st
{
    int top;
    int data[maxsize];
}stack,*pstack;
void push(pstack s,int x)
{
    if(s->top==(maxsize-1))
        printf("栈满\n");
    else
    {
        s->top++;
        s->data[s->top]=x;
    }
}
void pop(pstack s,int *y)
{
    if(s->top==-1)
        printf("栈空\n");
    else
    {
        *y=s->data[s->top];
        s->top--;
    }
}
pstack init()
{
    pstack s;
    s=(pstack)malloc(sizeof(stack));
    if(s)
    {
        s->top=-1;
    }
    return s;
}

int compute(char s[])
{
    int i=0,len,flag;
    int b,c,d,e;
    len=strlen(s);
    pstack st=init();
    while(i='0'&&s[i]<='9')
        {
            b*=10;
            b+=s[i]-'0';
            i++;
            flag=1;
        }
        if(flag)
        {
            push(st,b);
        }
        else if(s[i]=='+'||s[i]=='-'||s[i]=='/'||s[i]=='*')
        {
            pop(st,&c);
            pop(st,&d);
            switch(s[i])
            {
            case '+':
                e=c+d;break;
            case '-':
                e=d-c;break;
            case '/':
                e=d/c;break;
            case '*':
                e=d*c;break;
            }
            push(st,e);
            i++;
        }
        else
            i++;
    }
    int result=st->data[st->top];
    return result;
}
int main()
{
    char s[20];
    int i,n,len;
    gets(s);
    n=compute(s);
    printf("%d",n);
    return 0;
}

逆波兰式求值(用链栈求解)_第1张图片

你可能感兴趣的:(编程)