#include <bits/stdc++.h>
using namespace std;
typedef int ElemType;
ElemType level[1123];
char st[1123];
char res[1123];
class Stack{
private:
ElemType *up; /// 指向栈顶
ElemType *base; /// 指向栈底
ElemType length; /// size
public:
Stack(); /// 初始化实现栈的初始化
void push(ElemType x); /// 入栈
void pop(); /// 出栈
ElemType top(){return *(up - 1);} /// 返回栈顶元素
ElemType size(){return length;} /// 返回栈的大小
bool empty(){return 0 == length;} /// 判断栈是否为空
};
bool levelcmp(char a, char b); /// 优先级比较
int main()
{
level['+'] = level['-'] = 1;
level['*'] = level['/'] = 2;
while(cin >> st)
{
Stack Q;
int p = 0;
for(int i = 0; st[i]; i++)
{
if(st[i] == '#')
{
break;
}
if(isalnum(st[i]))
{
res[p++] = st[i];
}
else{
if(Q.empty() || Q.top() == '(' || st[i] == '(')
{
Q.push(st[i]);
}
else if(st[i] == ')'){
while(!Q.empty() && Q.top() != '(')
{
res[p++] = Q.top();
Q.pop();
}
if(!Q.empty())
{
Q.pop();
}
}
else{
while(!Q.empty() && !levelcmp(st[i],Q.top()))
{
res[p++] = Q.top();
Q.pop();
}
Q.push(st[i]);
}
}
}
while(!Q.empty())
{
res[p++] = Q.top();
Q.pop();
}
res[p] = 0;
puts(res);
}
return 0;
}
Stack::Stack(){ /// 栈的初始化的具体实现
base = new ElemType;
up = base;
length = 0;
}
void Stack::push(ElemType x){ /// 入栈函数的具体实现
*up++ = x;
length++;
}
void Stack::pop(){ /// 出栈函数的具体实现
up--;
length--;
}
bool levelcmp(char a, char b){ /// 符号优先级比较的具体实现
return level[(int) a] > level[(int) b];
}
栈与队列:一般算术表达式转换成后缀式
最新推荐文章于 2021-05-26 18:30:06 发布