#include <iostream>
#include <cctype>
#include <string>
using namespace std;
const int MAXSIZE = 100;
typedef char Datatype;
typedef struct{ int top; Datatype data[MAXSIZE]; }Seqstack, *pSeqstack;
pSeqstack init(void)
{
pSeqstack s;
s = (pSeqstack)malloc(sizeof(Seqstack));
if (s)
s->top = -1;
return(s);
}
int empty(pSeqstack s)
{
if (s->top == -1)
return(1);
else
return(0);
}
int push(pSeqstack s, Datatype x)
{
if (s->top == MAXSIZE - 1)
return(0);
else
{
++s->top;
s->data[s->top] = x;
return(1);
}
}
int pop(pSeqstack s, Datatype *x)
{
if (empty(s))
return(0);
else
{
*x = s->data[s->top];
--s->top;
return(1);
}
}
int get_top(pSeqstack s, Datatype *x)
{
if (empty(s))
return(0);
else
{
*x = s->data[s->top];
return(1);
}
}
/********************************************************************************
使用一个栈用来存放操作数,从左向右依此扫描表达式,若是操作数则直接入栈,
若是操作符则取出栈中两个操作数做运算在放入,表达式扫描结束后,栈顶元素就是结果。
********************************************************************************/
//double postfix_exp(const char *a)
//{
// double t0, t1, t2;
// pSeqstack s=init();
// while (a && *a)
// {
// if (isalnum(*a))
// push(s, *a-'0');
// else
// {
// pop(s, &t2);
// pop(s, &t1);//注意取出操作数的顺序
// switch (*a)
// {
// case '+' : t0 = t1 + t2; break;
// case '-' : t0 = t1 - t2; break;
// case '*' : t0 = t1 * t2; break;
// case '/' : t0 = t1 / t2; break;
// case '%' : t0 = (int)t1 % (int)t2; break;
// }
// push(s, t0);
// }
// a++;
// }
// get_top(s, &t0);
// return(t0);
//}
/********************************************************************************
将中缀表达式转换为后缀表达式:
从左向右扫描表达式,若是操作数,则输出;
若不是操作数:
若当前栈顶为#,且该操作符为#,则终止;
否则将该操作符压栈;
若当前栈顶不是#,
若栈顶元素是‘(’,并且当前元素是‘)’,则去括号;
否则将操作符压栈;
若栈顶元素不是‘(’,则比较两个元素优先级,
若栈顶元素优先级高,则输出当前操作符;
否则,压栈操作符。
********************************************************************************/
int get_prio(char op)
{
switch (op)
{
case '#':return(1);
case ')':return(2);
case '+':
case '-':return(3);
case '*':
case '/':return(4);
case '(':return(5);
default:return(0);
}
}
string mid_to_post(const char *a)
{
pSeqstack s = init();
string re;
char ch, temp;
while (*a)
{
if (*a >= '0' && *a <= '9')
re += *a;
else
{
get_top(s, &ch);
if (ch == '(')
{
if (*a == ')')
pop(s, &temp);
else
push(s, *a);
}
else
{
while (get_prio(ch) >= get_prio(*a) && ch != '(' && !empty(s))
{
re += ch;
pop(s, &temp);
get_top(s,&ch);
}
if (ch == '(' && *a == ')')
pop(s, &temp);
else
push(s, *a);
}
}
a++;
}
while (!empty(s))
{
pop(s, &ch);
re += ch;
}
return re;
}
int main()
{
char* r = "1285-*+42/-";
char* t = "1+2*(8-5*(2-5))-4/2";
cout << r << endl;
string s = mid_to_post(t);
cout << s << endl;
//double rs = postfix_exp(s);
//cout << rs << endl;
while (1)
{
}
return(1);
}
中缀表达式转成后缀表达式 后缀表达式求值
最新推荐文章于 2020-04-19 22:36:52 发布