- 设立暂存运算符的栈;
- 设表达式的结束符为“#”,
予设运算符栈的栈底为“#” - 若当前字符是操作数,
则直接发送给后缀式; - 若当前表达式运算符的优先数高于栈顶运算符,则进栈;
- 否则,退出栈顶运算符发送给后缀式;
- “(” 对它前后的运算符起隔离作用,
“)”可视为自相应左括弧开始的表达式的结束符
#include <iostream>
#include <stdio.h>
#include <map>
#include <string>
#define STACK_INIT_SIZE 100
#define BUFFER_LENGTH 100
#define OK 1
#define ERROR -1
typedef char ElemType;
typedef int Status;
using namespace std;
map<char, int> GetPriority;
typedef struct {
ElemType *base;
ElemType *top;
int stacksize;
} SqStack;
Status InitStack(SqStack &S)
{
S.base = new ElemType[STACK_INIT_SIZE];
if (!S.base) exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
Status Push(SqStack &S, ElemType e)
{
if (S.top - S.base >= S.stacksize)
return OVERFLOW;
S.top++;
*S.top = e;
return OK;
}
Status Pop(SqStack &S)
{
if (S.top == S.base) return ERROR;
S.top--;
return OK;
}
void RecurvePop(SqStack &S, ElemType e,string &s)
{
int topprior = GetPriority[*S.top];
int prior = GetPriority[e];
if (topprior > prior ) return;
s += *S.top;
Pop(S);
RecurvePop(S, e,s);
}
bool StackEmpty(const SqStack &S)
{
if (S.top == S.base) return true;
else return false;
}
string TransformRPN(char exp[],int len)
{
string s;
SqStack S;
InitStack(S); Push(S, '#');
for (int i = 0; i < len; i++)
{
char ch = exp[i];
int prio = GetPriority[ch];
if (prio == 0)
s += ch;
else {
if (prio == GetPriority['('])
Push(S, ch);
else if (prio == GetPriority[')']){
RecurvePop(S, ch,s);
Pop(S);
}
else {
int topprio = GetPriority[*S.top];
//先判断top的优先级比现在这个操作符高还是低
if (prio >= topprio)
RecurvePop(S, ch,s);
Push(S, ch);
}
}
}
RecurvePop(S, '?', s);
return s;
}
void InitMap()
{
//读入操作符ch,如果栈顶的元素top即上一个操作符的优先级比ch低或相等,就输出top,递归,直到碰到优先级比ch高的;
//如果栈顶的元素top即上一个操作符的优先级比ch高,那就把ch Push到栈上去;
GetPriority['*'] = 2; GetPriority['/'] = 2;
GetPriority['+'] = 3; GetPriority['-'] = 3;
GetPriority[')'] = 4; GetPriority['('] = 5;
GetPriority['?'] = 7;//结束之后通过递归全部pop
GetPriority['#'] = 8;//Stack最底层的,确保Pop不出界
}
int main()
{
InitMap();
char buffer[BUFFER_LENGTH];
cin >> buffer;
cout << TransformRPN(buffer, strlen(buffer));
system("pause");
return 0;
}