一、题目及分析
表达式求值是程序设计语言编译的一个最基本问题,其中任何一个表达式都是由操作数、运算符(±*/)、界限符(#,(,),[,] )组成。运算符和界限符统称算符。算符的优先级关系为(数学角度上):
代码:
#include <iostream>//ZJJ数据据结构-栈3.2.5
#define STACK_INIT_SIZE 100//存储空间初始分配量
#define STACKINCREMENT 10//分配增量
typedef struct {
char* base;
char* top;
int stacksize;
}Stack;
void InitStack(Stack* s) {
s->base = (char*)malloc(STACK_INIT_SIZE * sizeof(char));
if (!s->base) {
exit(1);
}
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
}
char GetTop(Stack* s) {
if (s->top == s->base) {
return 0;
}
return *(s->top - 1);
}
void Push(Stack* s, char e) {//插入元素e为新的栈顶元素
if (s->top - s->base >= s->stacksize) {//如果栈满,扩充空间
s->base = (char*)realloc(s->base, (s->stacksize + STACKINCREMENT) * sizeof(char));
if (!s->base) {
exit(1);
}
s->top = s->base + s->stacksize;
s->stacksize += STACKINCREMENT;
}
*s->top++ = e;//赋值后栈顶指针+1
}
char Pop(Stack* s) {//删除栈顶元素
if (!s->base || s->top == s->base) {
std::cout << "栈创建失败" << std::endl;
exit(0);
}
return *(--s->top);//栈顶指针-1,给e赋值
}
bool fuhao(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '#' || c == '(' || c == ')';
}
char Priority(char a, char b) {
if (a == '+' || a == '-') {
if (b == '*' || b == '/' || b == '(')
return '<';
else
return'>';
}
if (a == '*' || a == '/') {
if (b == '(')
return '<';
else
return'>';
}
if (a == '(') {
if (b == ')')
return '=';
else
return'<';
}
if (a == ')') {
return '>';
}
if (a == '#') {
if (b == '#')
return '=';
else return '<';
}
}
char Count(char a, char x, char b) {//进行运算的函数
switch (x) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
}
}//Operator
char Operate() {
Stack OPTR;
Stack OPND;
InitStack(&OPTR);
InitStack(&OPND);
Push(&OPTR, '#');
char c = getchar();
while (c != '#' || GetTop(&OPTR) != '#') {
if (!fuhao(c)) {
Push(&OPND, c - '0');
c = getchar();
}
else {
switch (Priority(GetTop(&OPTR), c)) {
case'<': {
Push(&OPTR, c);
c = getchar();
break;
}
case'>': {
char b = Pop(&OPTR);
char a = Pop(&OPND);
char c = Pop(&OPND);
Push(&OPND, Count(a, b, c));
break;
}
case'=': {
Pop(&OPTR);
c = getchar();
break;
}
}
}
}
return GetTop(&OPND);
}
int main() {
char c = Operate();
std::cout << int(c) << std::endl;
return 0;
}
/*
char Operate() {
Stack OPTR, OPND;//OPTR:运算符栈 OPND:运算数栈
char c, x;
InitStack(&OPTR);
Push(&OPTR, '#');
InitStack(&OPND);
c = getchar();
while (c != '#' || GetTop(&OPTR) != '#') {
if (!fuhao(c)) {
Push(&OPND, c - '0'); //不是运算符,进入运算数栈。
c = getchar();
}
else
switch (Priority(GetTop(&OPTR), c)) {
case '<': {
Push(&OPTR, c);
c = getchar();
break;//栈顶元素优先级低
}
case '=': {
Pop(&OPTR);
c = getchar();
break;//栈顶元素优先级低
}
case '>':
char x = Pop(&OPTR);
char b = Pop(&OPND);
char a = Pop(&OPND);
Push(&OPND, Count(a, x, b));
break;
}
}
return GetTop(&OPND);
}
*/
运行结果:
有无欠缺的,欢迎指正。