int precede(char c)
{
    switch(c)
    {
    case '+':
    case '-':return 1;
    case '*':
    case '/':return 2;
    default:return 0;
    }
}

int getvalue(char c,int a,int b)
{
    switch(c)
    {
    case '+':return b+a;
    case '-':return b-a;
    case '*':return b*a;
    case '/':return b/a;
    }
    return 0;
}

bool isnum(char c)
{
    if(c>='0' && c<='9'||c>='a'&&c<='z'||c>='A'&&c<='Z')
        return 1;
    else
        return 0;
}

int strtonum(char s[],int &i)
{
    int a=0;
    a=s[i]-'0';
    i++;
    while(isnum(s[i]))
    {
        a=a*10+s[i]-'0';
        i++;
    }
    return a;
}

void change(char c[],char s[])
{
    int i,cnt=0,len=strlen(c);
    s[0]='#';
    for(i=0;i<len;)
    {
        if((c[i]=='+' || c[i]=='-') && s[cnt]=='#')
        {
            s[++cnt]='0';
            s[++cnt]=c[i];
            i++;
        }
        else if(c[i]=='(')
        {
            s[++cnt]=c[i];
            i++;
            while(c[i]==' ') i++;
            if(c[i]=='+' || c[i]=='-')
            {
                s[++cnt]='0';
                s[++cnt]=c[i];
                i++;
            }
        }
        else if(c[i]==' '||c[i]=='\t') i++;
        else  {s[++cnt]=c[i];i++;}
    }
    s[++cnt]='';
}

int result(char s[])
{
    stack <char> ope;
    stack <int> nd;
    char c;
    int a,b,ans;
    int i,j=0,len=strlen(s);
    for(i=1;i<len;)
    {
        if(isnum(s[i]))
        {
            a=strtonum(s,i);
            nd.push(a);

        }
        else if(s[i]=='('){ ope.push('(');i++;}
        else if(s[i]==')')
        {
            while(ope.top()!='(')
            {
                c=ope.top();ope.pop();
                a=nd.top();nd.pop();
                b=nd.top();nd.pop();
                ans=getvalue(c,a,b);
                nd.push(ans);
            }

            ope.pop();
            i++;
        }
        else if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/')
        {
            if(!ope.empty() && precede(s[i])<=precede(ope.top()))//若当前符号优先级比栈里边的小,则一直弹栈
            {
                c=ope.top();ope.pop();
                a=nd.top();nd.pop();
                b=nd.top();nd.pop();
                ans=getvalue(c,a,b);
                nd.push(ans);
            }
            else
            {
                ope.push(s[i]);
                i++;
            }
        }
        else i++;
    }
    while(!ope.empty())
    {
        c=ope.top();ope.pop();
        a=nd.top();nd.pop();
        b=nd.top();nd.pop();
        ans=getvalue(c,a,b);
        nd.push(ans);
    }
    return nd.top();
}
不是本人之作、、、

发表评论

电子邮件地址不会被公开。

Post Navigation