目录:
- 代码:
- 分析:
- 汇编:
代码:
LinkList.h
LinkList.c
LinkStack.h
LinkStack.c
栈-线性表
main.c
#include <stdio.h>
#include "LinkStack.h"//该程序用栈来计算算式
/*比如:1*5+6/(5-3) 可以转换成 15*653-/+ 字符串进行运算注意:每个数只能是一位数*/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]));//将数值转成地址进栈 9转成000009}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/+"));getchar();return 0;
}
分析:
汇编: