#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <cstdlib>
#include <cctype>
#include <cstring>
using namespace std;
vector<string> preParse(char *str) //对中缀表达式进行预处理,分离出每个token
{
vector<string> tokens;
int len = strlen(str);
char *p = (char *)malloc((len+1)*sizeof(char)); //注意不要用 char *p = (char *)malloc(sizeof(str))来申请空间
int i=0,j=0;
while(i<len) //去除表达式中的空格
{
if(str[i]==' ')
{
i++;
continue;
}
p[j++] = str[i++];
}
p[j]='\0';
j=0;
len = strlen(p);
while(j<len)
{
char temp[2];
string token;
switch(p[j])
{
case '+':
case '*':
case '/':
case '(':
case ')':
{
temp[0] =p[j];
temp[1] = '\0';
token=temp;
tokens.push_back(token);
break;
}
case '-':
{
if(p[j-1]==')'||isdigit(p[j-1])) //作为减号使用
{
temp[0] =p[j];
temp[1] = '\0';
token=temp;
tokens.push_back(token);
}
else //作为负号使用
{
temp[0] ='#';
temp[1] = '\0';
token=temp;
tokens.push_back(token);
}
break;
}
case '0': //是数字
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
i = j;
while(isdigit(p[i])&&i<len)
{
i++;
}
char *opd = (char *)malloc(i-j+1);
strncpy(opd,p+j,i-j);
opd[i-j]='\0';
token=opd;
tokens.push_back(token);
j=i-1;
free(opd);
break;
}
default:
{
cout << "input error!";
tokens.clear();
return tokens;
}
}
j++;
}
free(p);
return tokens;
}
int Precedence(string op1, string op2)
{
if (op1 == "(")
{
return -1;
}
if (op1 == "#")
{
return 1;
}
if (op1 == "+" || op1 == "-")
{
if (op2 == "*" || op2 == "/"|| op2 == "#")
{
return -1;
}
else
{
return 0;
}
}
if (op1 == "*" || op1 == "/")
{
if(op2 == "#")
{
return -1;
}
else
return 1;
}
}
vector<string> toSuffix(char *str) //转变为后缀形式
{
vector<string> tokens = preParse(str);
int i=0;
int size = tokens.size();
if(size ==0)
{
return tokens;
}
vector<string> suffix; //存储后缀表达式
stack<string> optStack; //存储操作符
for(i=0; i<size; i++)
{
string token = tokens[i];
if(token=="#"||token=="+"||token=="-"||token=="*"||token=="/")
{
if(optStack.size()==0) //如果操作符栈为空
{
optStack.push(token);
}
else
{
while ((optStack.size()!=0) && Precedence(optStack.top(), token) >= 0)
{
string topOpt = optStack.top();
suffix.push_back(topOpt);
optStack.pop();
}
optStack.push(token);
}
}
else if(token=="(")
{
optStack.push(token);
}
else if(token==")")
{
while(optStack.top()!="(")
{
string topOpt = optStack.top();
suffix.push_back(topOpt);
optStack.pop();
}
optStack.pop();
}
else //如果是操作数,直接入操作数栈
{
suffix.push_back(token);
}
}
while(optStack.size()!=0)
{
string topOpt = optStack.top();
suffix.push_back(topOpt);
optStack.pop();
}
return suffix;
}
int main(int argc, char *argv[])
{
char *str = "((31+5*2)+3)/5+(-6)/4*2+3";
vector<string> suffix = toSuffix(str);
int size = suffix.size();
for(int i=0; i<size; i++)
cout<<suffix[i]<<" ";
cout<<endl;
return 0;
}
允许大于10、允许为负数、带输入检测 :非操作符及‘0’-‘9’。