【数据结构】中缀表达式的实现

来源:互联网 发布:查看淘宝关键词搜索量 编辑:程序博客网 时间:2024/06/06 08:48
#include<stack>
#include<vector>
#include<string>
#include<iostream>


using namespace std;


vector<string> Pre(const string a)//pre process with string.
{
vector<string> strs;
int l = a.length();
int i = 0;
for (i = 0; i < l; i++)
{
char temp[2];
string str;
temp[0] = a[i];
temp[1] = '\0';
str = temp;
strs.push_back(str);
}
return strs;
}


int Grade(const string op)//get priority.
{
int grade;
if (op == "*" || op == "/")
grade = 2;
else if (op == "+" || op == "-")
grade = 1;
else
grade = 0;
return grade;
}


void calculate(stack<int> &num, string op)//calculate
{
if(op == "+")
{
int a = num.top();
num.pop();
int r = num.top() + a;
num.pop();
num.push(r);
}
else if(op == "-")

int a = num.top();
num.pop();
int r = num.top() - a;
num.pop();
num.push(r);
}
else if(op == "*")
{
int a = num.top();
num.pop();
int r = num.top() * a;
num.pop();
num.push(r);
}
else if (op == "/")
{
int a = num.top();
num.pop();
int r = num.top() / a;
num.pop();
num.push(r);
}
}


int End(string &a)
{
stack<int> opd;//number stack
stack<string> opt;//char stack
vector<string> str = Pre(a);
int i = 0;
int l = str.size();
for (i = 0; i < l; i++)
{
string s = str[i];
if (s == "+" || s == "-" || s == "*" || s == "/")
{
if (opt.empty())// if char-stack is empty,push.
{
opt.push(s);
}
else
{
int grade_s = Grade(s);
int grade_top = Grade(opt.top());
if(grade_s>grade_top)//if s is +,-,*,/ ,compare priority and calculate.
{
opt.push(s);
}
else {
while (grade_s <= grade_top)
{
string opt_top = opt.top();
opt.pop();
calculate(opd, opt_top);
if (opt.size() > 0)
grade_top = Grade(opt.top());
else
break;
}
opt.push(s);//until s's priority > top's ,push.
}
}
}
else if (s == "(")
{
opt.push(s);
}
else if (s == ")")
{
while (opt.top() != "(")//if top not ( ,calculate.
{
string opt_top = opt.top();
calculate(opd, opt_top);
opt.pop();
}
opt.pop();//else top is ( ,pop.
}
else//if s is num ,push opd.
{
opd.push(atoi(s.c_str()));//transfer form.
}
}
while (opt.size() != 0)
{
string opt_top = opt.top();
calculate(opd, opt_top);
opt.pop();
}
return opd.top();
}


void main()
{
string m;
cout << "plz input m:" << endl;
cin >> m;
cout << "result is:" << End(m) << endl;
}
1 0
原创粉丝点击