NYOJ 35 表达式求值【栈的应用】

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

题意:给一个中缀表达式 求出表达式的值

操作符优先级:(从大到小) ‘(’ ——   ‘ * ’ 或 ‘ / ’ ——   '+'  或  ‘-’ ——  ‘ )’  ;(把括号也看作操作符)

思路:用两个栈,一个操作符栈,一个数据栈,顾名思义,数据栈存表达式的数据,操作符栈存 ()+ - * /  等。将中缀表达式转换为后缀表达式,在转换的过程中求表达式的值!具体步骤如下:(下面思路假设数据都是一位数的整数,便于理解,具体数字处理在代码中体现)

先将 一个’=‘ 放入 操作符栈

1:读取表达式的一个字符;

2:   若为数字存入数据 栈 转至1;

3:若为操作符:比较操作符栈顶 和 该操作符的 优先级  

      ① pk函数返回值 为 ’>‘(若操作符栈顶优先级大于或等于该操作符的优先级):栈顶操作符出栈(假设操作符为-) ,从数据栈出两个数据(假设第一个是y,第二个 是x),计算值(x-y),注意数据顺序!!将值放入 数据栈!转至 3;

      ② pk函数返回值为’<‘    (若操作符栈顶优先级小于该操作符的优先级):  讲该 操作符放入 操作符栈,转至 1;

      ③ pk函数返回值为’=‘    (具体看代码) 将操作符栈顶的操作符出栈,转至1;

4:输出数据栈栈顶值即可!

AC代码:

 
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stack>
using namespace std;
char pk(char c1,char c2)
{
	if(c1=='+'||c1=='-')
	{
		if(c2=='+'||c2=='-'||c2==')'||c2=='=')
			return '>';
		else
			return '<';
	}
	else if(c1=='*'||c1=='/')
	{
		if(c2=='+'||c2=='-'||c2=='*'||c2=='/'||c2==')'||c2=='=')
			return '>';
		else
			return '<';
	}
	else if(c1=='('||c1=='=')
	{
		if((c1=='('&&c2==')')||(c1=='='&&c2=='='))
			return '=';
		else
			return '<';
	}
}
double oper(double x,char c,double y)
{
	if(c=='+') return x+y;
	else if(c=='-') return x-y;
	else if(c=='*') return x*y;
	else return x/y;
}
int main()
{
	int a,i,j,n;
	scanf("%d",&n);
	while(n--)
	{
		char str[2000];
		char ok[200];
		int end=0,loop=0;
		stack<char>SC;
		SC.push('=');
		stack<double>S;
		scanf("%s",str);
		for(i=0;i<strlen(str);)
		{
			if(str[i]=='='&&SC.top()=='=')
				break;
			if(str[i]>='0'&&str[i]<='9'||str[i]=='.')
			{
				ok[end++]=str[i];
				loop=1;
				i++;
				continue;
			}
			if(loop)
			{
				ok[end]='\0';
				double x=atof(ok);
				end=0;
				loop=0;
				S.push(x);
			}
			switch(pk(SC.top(),str[i]))
			{
			case '<':SC.push(str[i]);i++;break;
			case '=':SC.pop();i++;break;
			case '>':
				double x,y;
				y=S.top();S.pop();
				x=S.top();S.pop();
				char c =SC.top();SC.pop();
				S.push(oper(x,c,y));
				break;
			}
		}
		printf("%.2lf\n",S.top());
	}
}        


发布了81 篇原创文章 · 获赞 184 · 访问量 18万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章