nyoj 表达式求值--栈的应用

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=35

思路:用栈模拟数的四则运算;初始化各种运算符之间的优先级;

代码如下:

#include "stdio.h"
#include "string.h"
#include "stack"
using namespace std;

#define N 2005

char str[N];
int OPS[256];
char table[8][8]={">><<<>>",">><<<>>",">>>><>>",">>>><>>","<<<<<=<",">>>>>>>","<<<<<<="};
//上面语句定义了操作符之间的优先级,从0~6依次为+-*/()=七种运算符

double Calculate(char ch,double x1,double x2)  
{
    if(ch=='+')
        return x1+x2;
    else if(ch=='-')
        return x1-x2;
    else if(ch=='*')
        return x1*x2;
    else if(ch=='/')
        return x1/x2;
}

int main()
{
    int T;
    int i,j;
    int len;
    memset(OPS,-1,sizeof(OPS));
    OPS['+'] = 0;
    OPS['-'] = 1;
    OPS['*'] = 2;
    OPS['/'] = 3;
    OPS['('] = 4;
    OPS[')'] = 5;
    OPS['='] = 6;
    scanf("%d",&T);
    getchar();
    while(T--)
    {
        scanf("%s",str+1);
        str[0] = '=';
        stack q;  //操作数栈
        stack t;  //操作符栈
        len = strlen(str);
        for(i=0; i')  //前一个操作符先执行,则先执行前一个操作符,再加入这个操作符
                    {
                        double x2 = q.top(); 
                        q.pop();
                        double x1 = q.top(); 
                        q.pop();
                        char ch = t.top(); 
                        t.pop();
                        double x = Calculate(ch,x1,x2); //运算这两个数
                        q.push(x);
                    }
                    else if(table[OPS[ch1]][OPS[ch2]]=='<')  //前一个操作符后执行,则直接将当期这个操作如入栈
                        t.push(str[i++]);
                    else if(table[OPS[ch1]][OPS[ch2]]=='=') //'='的情况表示括号对,后者等号对,将这两个操作符都消去。
                        t.pop(), i++;
                }
            }
        }
        printf("%.2lf\n",q.top());
        q.pop();
    }
    return 0;
}



你可能感兴趣的:(数据结构)