#include <iostream>
#include <cctype>
using namespace std;
const int LEN = 50;
typedef char T;
class Stack
{
private:
T data[LEN];
int sz;
public:
Stack():sz()
{
}
void push(const T& d) throw(const char*)
{
if(isFull())
{
throw "满";
}
data[sz++] = d;
}
void pop() throw (const char*)
{
if(isEmpty())
{
throw "空";
}
sz--;
}
T top()
{
if(isEmpty())
{
throw "空";
}
return data[sz-1];
}
bool isEmpty()
{
return 0==sz;
}
bool isFull()
{
return LEN == sz;
}
int size()
{
return sz;
}
};//end of class
bool prior(char c1,char c2)
{
return (c1 == '*' || c1 == '/') && (c2 == '+' ||c2 == '-');
}
int main()
{
string str = "(1+2*3/2)/4+(5+9)/7";
Stack res; //结果栈
Stack exp; //运算符栈
char ch;
for(int i = 0; i < str.length(); i++)
{
ch = str[i];
if(ch >= '0' && ch <='9')
{
res.push(ch);
}
else if('(' == ch)
{
exp.push(ch);
}
else if(')' == ch)
{
while(exp.top() != '(')
{
res.push(exp.top());
exp.pop();
}
exp.pop();
}
else
{
while(!exp.isEmpty() && exp.top() != '('
&& !prior(ch,exp.top()))
{
res.push(exp.top());
exp.pop();
}
exp.push(ch);
}
}
while(!exp.isEmpty())
{
res.push(exp.top());
exp.pop();
}
while(!res.isEmpty())
{
cout << res.top();
res.pop();
}
cout << endl;
}
中缀表达式转后缀表达式
最新推荐文章于 2024-04-12 09:59:55 发布