7-82 逆波兰表达式求值 (20 分)

7-82 逆波兰表达式求值 (20 分)

逆波兰表示法是一种将运算符(operator)写在操作数(operand)后面的描述程序(算式)的方法。举个例子,我们平常用中缀表示法描述的算式(1 + 2)*(5 + 4),改为逆波兰表示法之后则是1 2 + 5 4 + *。相较于中缀表示法,逆波兰表示法的优势在于不需要括号。
请输出以逆波兰表示法输入的算式的计算结果。

输入格式:

在一行中输入1个算式。相邻的符号(操作数或运算符)用1个空格隔开。

输出格式:

在一行中输出计算结果。

限制:

2≤算式中操作数的总数≤100
1≤算式中运算符的总数≤99
运算符仅包括“+”、“-”、“*”,操作数、计算过程中的值以及最终的计算结果均在int范围内。

输入样例1:

4 3 + 2 -

输出样例1:

5

输入样例2:

1 2 + 3 4 - *

输出样例2:

-3

 C++代码(调用STL-stack库):

#include<iostream>
#include<stack>
#include<cstdlib>
using namespace std ;
int main()
{
	stack<int> s ;
	char str[20] ;
	int x ;
	int y ; 
	while(scanf("%s",str)!=EOF)
	{
		if(str[0]=='+')
		{
			x = s.top() ;
			s.pop() ;
			y = s.top() ;
			s.pop() ;
			s.push(x+y) ;
		}
		else if(str[0]=='-')
		{
			x = s.top() ;
			s.pop() ;
			y = s.top() ;
			s.pop() ;
			s.push(y-x) ;	
		}
		else if(str[0]=='*')
		{
			x = s.top() ;
			s.pop() ;
			y = s.top() ;
			s.pop() ;
			s.push(y*x) ;	
		}
		else if(str[0]=='/')
		{
			x = s.top() ;
			s.pop() ;
			y = s.top() ;
			s.pop() ;
			s.push(y/x) ;	
		}
		else
			{
				x = atoi(str) ;//将字符串类型数字转换为int型
				s.push(x) ;
			}
	}
	printf("%d",s.top()) ;
	return 0 ;
 } 

C语言代码:

#include<iostream>
#include<stack>
#include<cstdlib>
using namespace std ;
int main()
{
	stack<int> s ;
	char str[20] ;
	int x ;
	int y ; 
	while(scanf("%s",str)!=EOF)
	{
		if(str[0]=='+')
		{
			x = s.top() ;
			s.pop() ;
			y = s.top() ;
			s.pop() ;
			s.push(x+y) ;
		}
		else if(str[0]=='-')
		{
			x = s.top() ;
			s.pop() ;
			y = s.top() ;
			s.pop() ;
			s.push(y-x) ;	
		}
		else if(str[0]=='*')
		{
			x = s.top() ;
			s.pop() ;
			y = s.top() ;
			s.pop() ;
			s.push(y*x) ;	
		}
		else if(str[0]=='/')
		{
			x = s.top() ;
			s.pop() ;
			y = s.top() ;
			s.pop() ;
			s.push(y/x) ;	
		}
		else
			{
				x = atoi(str) ;//将字符串类型数字转换为int型
				s.push(x) ;
			}
	}
	printf("%d",s.top()) ;
	return 0 ;
 } 

猜你喜欢

转载自blog.csdn.net/qq_41591279/article/details/88075207
今日推荐