*本文为(186-56)/(4+2)2的后缀算法的设计与实现
(此处采用的是顺序栈的存储结构)
运行结果为
栈的顺序存储结构以及基本运算
typedef struct {
ElemType data[MaxSize];
int top;
}SqStrack;
//(1)初始化栈
SqStrack* InitStrack() {
SqStrack* s = (SqStrack*)malloc(sizeof(SqStrack));
s->top = -1;
return s;
}
//(2)销毁栈
void DestroyStract(SqStrack* s) {
free(s);
}
//(3)判断栈是否为空
bool StactEmpty(SqStrack* s) {
return(s->top == -1);
}
//(4)进栈
bool Push(SqStrack* s, ElemType e) {
if (s->top == MaxSize - 1)
return false;
s->top++;
s->data[s->top] = e;
return true;
}
//(5)出栈
bool Pop(SqStrack* s, ElemType &e) {
if (s->top == -1)
return false;
e = s->data[s->top];
s->top--;
return true;
}
//(6)取栈顶元素
bool GetTop(SqStrack* s, ElemType &e) {
if (s->top == -1)
return false;
e = s->data[s->top];
return true;
}
此处代码与compvalue()的顺序栈的存储结构,调用差不多,就不过多叙述,只需多加1(push1()这种样子修改)。
中缀表达式"(186-56)/(4+2)*2"转换为后缀表达式的基本过程
void trans(char* exp, char postexp[]) {
char e;
SqStrack* Optr= InitStrack();
int temp = 0;
int i = 0;
int j = 0;
while (exp[j] != '\0') {
//TODO
switch (exp[j]) {
case '(':
//TODO
Push(Optr, '(');
j++;
break;
case ')':
//TODO
Pop(Optr, e);
while (e != '(') {
postexp[i++] = e;
Pop(Optr, e);
//TODO
}
j++;
break;
case '+':
case '-':
while (!StactEmpty(Optr)) {
//TODO
Pop(Optr, e);
if (e != '(') {
//TODO
postexp[i++] = e;
Pop(Optr, e);
}
else {
Push(Optr, e);
break;
}
}
Push(Optr, exp[j]);
j++;
break;
case '*':
case '/':
while (!StactEmpty(Optr)) {
//TODO
Pop(Optr, e);
if (e != '(' && e !='+' && e != '-') {
//TODO
postexp[i++] = e;
Pop(Optr, e);
}
else {
Push(Optr, e);
break;
}
}
Push(Optr, exp[j]);
j++;
break;
default:
//TODO
if (exp[j] >= '0' && exp[j] <= '9') {
while (exp[j] >= '0' && exp[j] <= '9') {
//TODO
postexp[i++] = exp[j];
j++;
}
postexp[i++] = '#';
}
else
j++;
break;
}
}
while (!StactEmpty(Optr)) {
//TODO
Pop(Optr, e);
postexp[i++] = e;
}
postexp[i] = '\0';
DestroyStract(Optr);
}
后缀表达式“186#56#-4#2#+/2#*”的求值过程
double compvalue(char* postexp) {
double d, a, b, c, e;
// SqStrack1 * Opnd;
SqStrack1* Opnd= InitStrack1();
while (*postexp != '\0') {
//TODO
switch (*postexp) {
case '+':
//TODO
Pop1(Opnd, a);
Pop1(Opnd, b);
c = a + b;
Push1(Opnd, c);
break;
case '-':
//TODO
Pop1(Opnd, a);
Pop1(Opnd, b);
c = b - a;
Push1(Opnd, c);
break;
case '*':
//TODO
Pop1(Opnd, a);
Pop1(Opnd, b);
c = b * a;
Push1(Opnd, c);
break;
case '/':
//TODO
Pop1(Opnd, a);
Pop1(Opnd, b);
if (a != 0) {
//TODO
c = b / a;
Push1(Opnd, c);
break;
}
else
{
printf("\n\t除零错误!\n");
exit(0);
}
break;
default:
//TODO
d = 0;
while (*postexp >= '0' && *postexp <= '9') {
//TODO
d = 10 * d + *postexp - '0';
postexp++;
}
Push1(Opnd, d);
break;
}
postexp++;
}
GetTop1(Opnd, e);
DestroyStract1(Opnd);
return e;
}
主函数调用上述的算法
int main(){
//
char exp[]="(186-56)/(4+2)*2";
char postexp[MaxSize];
trans(exp,postexp);
printf("中缀表达式:%s\n",exp);
printf("后缀表达式:%s\n",postexp);
printf("表达式的值:%g\n",compvalue(postexp));
return 1;
}