表达式求值问题(包含两位数)

欢迎加qq群:453398542 学习讨论,会定期分享资料课程,解答问题。
 
表达式求值问题
【问题描述】
    给定一个算术表达式,对该表达式进行四则运算。
(1)以栈作为存储结构,一个栈存放操作符,一个栈存放操作数;
        (2)按字符串形式输入表达式;
        (3)最终结果放在操作数栈中并输出。
给定的表达式中,必须有包含两位数的数值。例如,给定的表达式为:(10+2)*6-12/3
#include<iostream>
using namespace std;
typedef struct SNode{
	int data;
	struct SNode *next;
}SNode,*LinkStack;
char Precede(char theta1,char theta2){
	//比较优先级 
	if(  (theta1=='(' && theta2==')'  ) || (theta1=='#' && theta2=='#') )
		return '=';
	else if( theta1=='(' || theta1=='#' || theta2=='('|| ( theta1=='+'||theta1=='-' )&&(theta2=='*'||theta2=='/') )
		return '<';
	else return '>';
}
int InitStack(LinkStack &S){
	S=NULL;
	return 1;
}
int StackEmpty(LinkStack S){
	if(!S)
		return 1;
	return 0;
}
int Push(LinkStack &S,char e){
	SNode *p=new SNode;
	if(!p){
		return -1;
	}
	p->data=e;
	p->next=S;
	S=p;
	return 1;
}
int Pop(LinkStack &S,char &e){
	SNode *p;
	if(!S)
		return 0;
	e=S->data;
	p=S;
	S=S->next;
	delete p;
	return 1;
}
int GetTop(LinkStack &S,char &e){
	if(!S)
		return 0;
	e=S->data;
	return 1;
}
char Operate(char first,char theta,char second){
	//运算 
	switch(theta){
		case '+':
			return (first-'0')+(second -'0')+48;
		case '-':
			return (first-'0')-(second -'0')+48;
		case '*':
			return (first-'0')*(second -'0')+48;
		case '/':
			return (first-'0')/(second -'0')+48;
	}
}
char EvaluateExpression(){
	//结果 
	LinkStack OPTR,OPND;
	char ch,theta,a,b,x,top,k=0,count;
	InitStack(OPTR);//运算符 
	InitStack(OPND);//数和结果
	Push(OPTR,'#');
	cin>>ch;
	while(ch!='#'||(GetTop(OPTR,top),top!='#')){
		if(isdigit(ch)){
			//判断字符是否为阿拉伯数字 
			if(k>0){
				Pop(OPND,count);
				count=(count-'0')*10+(ch-'0')+48;
				Push(OPND,count);
			}
			else{
				Push(OPND,ch);
			}
			cin>>ch;
			k++;
		}
		else{
			k=0;
			GetTop(OPTR,top);
			switch(Precede(top,ch)){
				case '<':
					Push(OPTR,ch);
					cin>>ch;
					break;
				case '>':
					Pop(OPTR,theta);
					Pop(OPND,a);
					Pop(OPND,b);
					Push(OPND,Operate(b,theta,a));
					break;
				case'=':
					Pop(OPTR,x);
					cin>>ch;
					break;
			}
		}
	}
	GetTop(OPND,ch);
	return ch;
}
int main(){
	cout<<"输入表达式(以#结尾):"<<endl; 
	char res=EvaluateExpression();
	cout<<(int)(res-'0')<<endl;
}

 
 
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值