对任意给定的一个中缀算术表达式输出等价的后缀形式。(利用栈)
例如:1+2*3+(4*5+6)*7转换成
123*+45*6+7*+
#include <iostream>
#include <map>
#include <string>
using namespace std;
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType* base;
ElemType* top;
int stacksize;
}SqStack;
//栈初始化
Status initstack(SqStack& s)
{
s.base = new ElemType[MAXSIZE];
if (!s.base)
exit(OVERFLOW);
s.top = s.base;
s.stacksize = MAXSIZE;
return OK;
}
//判断栈是否为空
Status empty(SqStack& s)
{
if (s.top == s.base)
return OK;
else
return ERROR;
}
//入栈
Status push(SqStack& s, ElemType e)
{
if (s.top - s.base == s.stacksize)
return ERROR;
*s.top++ = e;
return OK;
}
//出栈
Status pop(SqStack& s, ElemType& e)
{
if (s.top == s.base)
return ERROR;
e = *--s.top;
return OK;
}
//仅出栈
Status pop(SqStack& s)
{
if (s.top == s.base)
return ERROR;
ElemType e;
e = *--s.top;
return OK;
}
//取栈顶元素
ElemType get_top(SqStack& s)
{
if (s.top != s.base)
return *(s.top - 1);
}
//后缀表达式1
void postfix(string in)
{
string post;
SqStack mark;
initstack(mark);
map<char, int> p;
p['+'] = 0;
p['-'] = 0;
p['*'] = 1;
p['/'] = 1;
int l = in.length();
for (int i = 0; i < l; i++)
{
switch (in[i])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
post.push_back(in[i]);
break;
}
case '+':
case '-':
case '*':
case '/':
{
if (!empty(mark))
{
char mark_top = get_top(mark);
while (mark_top != '(' && p[in[i]] <= p[mark_top])
{
post.push_back(mark_top);
pop(mark);
if (empty(mark))
{
break;
}
mark_top = get_top(mark);
}
}
push(mark, in[i]);
break;
}
case '(':
{
if (in[i - 1] >= '0' && in[i - 1] <= '9')
{
push(mark, '*');
}
push(mark, in[i]);
break;
}
case ')':
{
char mark_top = get_top(mark);
while (mark_top != '(')
{
post.push_back(mark_top);
pop(mark);
mark_top = get_top(mark);
}
pop(mark);
break;
}
}
}
while (!empty(mark))
{
post.push_back(get_top(mark));
pop(mark);
}
cout << post << endl;
}
int main()
{
/*SqStack s;
int a;
initstack(s);
push(s, 1);
push(s, 2);
push(s, 3);
push(s, 4);
push(s, 5);
pop(s, a);
cout << a << endl;
pop(s, a);
cout << a << endl;
a = get_top(s);
cout << a << endl;*/
//中后缀转换
string in;
cin >> in;
postfix(in);
return 0;
}