栈的应用——逆波兰表达式

0.概述
本文实现了以字符串形式输入逆波兰表达式(后缀表达式),实现求值得代码
表达式求值具体原理请参考我的另一篇博客:栈的应用——表达式求值.

1.代码实现:

后缀表达式求值:

//必须输入整数在10以内的正确后缀逆波兰表达式
#include<bits/stdc++.h>
using namespace std;

#define MaxSize 10 

//计算乘除加减结果 
int getResult(int b,int a,int op){
	int result;
	if(op==1){
		result=a+b;	
	}
	else if(op==2){
		result=a-b;	
	}
	else if(op==3){
		result=a*b;		
	}
	else if(op==4){	//代表除 
		result=a/b;		
	}
	return result;
} 

//表达式求值函数
int GetValue(string str,int len){
	int v[MaxSize];	//	定义 操作数栈 
	int top=-1;	//	定义指针 
	
	int result;//存储两个操作数结果 
	
	for(int i=0;i<len;i++){
		if(str[i]>='0'&&str[i]<='9'){ 
			top++; //指针+1 
			v[top]=str[i]-'0';	//非运算符,入栈 
		}
		else{
			if(str[i]=='+'){
				result=getResult(v[top],v[top-1],1);
				v[--top]=result;
			}
			else if(str[i]=='-'){
				result=getResult(v[top],v[top-1],2);
				v[--top]=result;
			}
			else if(str[i]=='*'){
				result=getResult(v[top],v[top-1],3);	//第一个出栈的为右操作数 
				v[--top]=result;	//将运算后的值入栈 
			}
			else if(str[i]=='/'){
				result=getResult(v[top],v[top-1],4);
				v[--top]=result;
			}
		} 
	} 
	return v[top];	//此时top应该为0 
} 

int main(){
	
	string str;	
	getline(cin,str);	//获取输入表达式字符串 
	
	int len=str.length();	//	获取表达式的长度 
	int result=GetValue(str,len);//	获取表达式的值
	
	cout<<"表达式的结果为:"<<result<<endl;
	
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值