首页 > 代码库 > 栈的应用---后缀运算法则
栈的应用---后缀运算法则
·对于数字:进栈
·对于符号:
·从栈中弹出右操作数
·从栈中弹出左操作数
·依据符号进行运算
·将运算结果压入栈中
·遍历结果:栈中唯一的数字为结果
伪算法
int compute (const char * exp)
{
创建栈
int i = 0;
While (exp[i] != ‘\0’)
{
if(数字)
输出
Else if (假设是符号)
{
Int right = 左操作数出栈(此时在栈顶)
Int left = 右操作数出栈 (此时栈顶)
Int result = 左操作数与有操作数关于运算符的结果
结果进栈
}
Else
报错
}
If (栈中仅仅有一个数字并且遍历完成)
结果出栈
Else
报错
Return 返回结果;
}
代码:
#include <stdio.h>
#include "LinkStack.h"
int isNumber(char c)
{
return (‘0‘ <= c) && (c <= ‘9‘);
}
int isOperator(char c)
{
return (c == ‘+‘) || (c == ‘-‘) || (c == ‘*‘) || (c == ‘/‘);
}
int value(char c)
{
return (c - ‘0‘);
}
int express(int left, int right, char op)
{
int ret = 0;
switch(op)
{
case ‘+‘:
ret = left + right;
break;
case ‘-‘:
ret = left - right;
break;
case ‘*‘:
ret = left * right;
break;
case ‘/‘:
ret = left / right;
break;
default:
break;
}
return ret;
}
int compute(const char* exp)
{
LinkStack* stack = LinkStack_Create();
int ret = 0;
int i = 0;
while( exp[i] != ‘\0‘ )
{
if( isNumber(exp[i]) )
{
LinkStack_Push(stack, (void*)value(exp[i]));
}
else if( isOperator(exp[i]) )
{
int right = (int)LinkStack_Pop(stack);
int left = (int)LinkStack_Pop(stack);
int result = express(left, right, exp[i]);
LinkStack_Push(stack, (void*)result);
}
else
{
printf("Invalid expression!");
break;
}
i++;
}
if( (LinkStack_Size(stack) == 1) && (exp[i] == ‘\0‘) )
{
ret = (int)LinkStack_Pop(stack);
}
else
{
printf("Invalid expression!");
}
LinkStack_Destroy(stack);
return ret;
}
int main()
{
printf("9 + (3 - 1) * 5 + 8 / 2 = %d\n", compute("931-5*+82/+"));
return 0;
}
与中缀转后缀合用。能够变成计算器的程序
栈的应用---后缀运算法则