用栈实现代数式的 加减乘除
样例 计算4+2*3-10/5
#include<iostream>
#include<list>
#include<vector>
#include<stack>
#include<string>
using namespace std;
//比较运算符的优先级
int MatchOper(char str1,char str2)
{
if(str1=='+'||str1=='-')
{
if(str2=='+'||str2=='-'||str2==')'||str2=='#')
return 1; //1代表str1优先级高
else return 3; //3代表str1优先级低,str2优先级高;2代表两者的优先级相等
}
else if(str1=='*'||str1=='/')
{
if(str2=='(') return 3;
else return 1;
}
else if(str1=='(')
{
if(str2==')') return 2;
else return 3;
}
else if(str1==')')
{
if(str2!='(') return 1;
else return 0; //0表示出错
}
else {
if(str2==')') return 0;
else if(str2=='#') return 2;
else return 3;
}
}
int operate(int a,char theta,int b)
{
int k=0;
if(theta=='+') k=a+b;
else if(theta=='-') k=a-b;
else if(theta=='*') k=a*b;
else if(theta=='/') k=a/b;
return k;
}
void main()
{
stack<char,list<char>>s2; //s1是数字栈,s2是符号栈
stack<int,vector<int>>s1;
char *s=new char[100];
cout<<"请输入表达式:"<<endl;
cin>>s;
int i=0,num=0;
int num1,num2;
s2.push('#');
while(s[i])
{
if((s[i]>='0')&&(s[i]<='9'))
{
while((s[i]>='0')&&(s[i]<='9'))//这里主要是为了处理两位数或高位数
{
num=10*num+s[i++]-'0';
}
s1.push(num);//如果是数字,则进栈s1,否则
//cout<<"数字进栈 "<<s1.top()<<"数字 "<<num<<endl;
num=0;
}
else //比较两个符号的优先级
{
char& ch=s2.top();
//cout<<"出现符号"<<s[i]<<endl;
switch (MatchOper(ch,s[i++]))
{
case 1: //栈顶元素优先级高(前者的优先级高)
num1=s1.top(); //得到s1的栈顶元素,第二个参加运算的数字
//cout<<"num1= "<<num1<<endl;
s1.pop(); //出栈
num2=s1.top(); //得到第一个参加运算的数字
//cout<<"num2= "<<num2<<endl;
s1.pop();
//cout<<"符号 "<<ch<<"优先级高于符号 "<<s[i-1]<<endl;
s1.push(operate(num2,ch,num1)); //将得到的结果压入栈中
//cout<<"将数据 "<<operate(num2,ch,num1)<<"压入栈中"<<endl;
s2.pop();
i--;
break;
case 2: //两者的优先级相等
//cout<<"符号 "<<ch<<"优先级等于符号 "<<s[i-1]<<endl;
//cout<<"此时出栈的符号是 "<<s2.top()<<endl;
s2.pop(); //直接出栈s2就好
break;
case 3: //后者的优先级高,直接将符号压入栈中就行
s2.push(s[i-1]);
//cout<<"符号 "<<ch<<"优先级低于符号 "<<s[i-1]<<endl;
//cout<<"此时入栈的符号是 "<<s2.top()<<endl;
break;
}
}
}
while(s2.top()!='#')//此时字符串处理完毕,但是栈内还有待处理的数据
{
char ch=s2.top();
s2.pop();
num2=s1.top();
s1.pop();
num1=s1.top();
s1.pop();
s1.push(operate(num1,ch,num2));
}
cout<<"结果为:"<<s1.top()<<endl;
}
浙公网安备 33010602011771号