简单表达式求值;仅支持±*/,且不支持负数,多位数~。逻辑没问题,数据结构选好后统统都可以解决
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define CAPACITY 100
typedef char Element;
typedef struct
{
int base;
int top;
int size;
Element stack[CAPACITY];
} Stack;
Stack init(Stack *s)
{
s->base = 0;
s->top = -1;
s->size = 0;
return *s;
}
Stack clean(Stack *s)
{
s->size = 0;
s->base = 0;
s->top = -1;
return *s;
}
bool push(Stack *s, Element e)
{
if (s->size >= CAPACITY)
{
printf("stack had full");
return false;
}
s->stack[++(s->top)] = e;
s->size++;
return true;
}
bool pop(Stack *s, Element *e)
{
if (s->size <= 0)
{
printf("Stack had null");
return false;
}
*e = s->stack[s->top];
s->top--;
s->size--;
return true;
}
Element getTop(Stack s)
{
return s.stack[s.top];
}
bool isEmpty(Stack s)
{
return s.size == 0 ? true : false;
}
int size(Stack s)
{
return s.size;
}
void expr(char *str, Stack Num_s, Stack Sign_s)
{
char buf[2];
int i = 0;
init(&Sign_s);
init(&Num_s);
while (str[i] != '\0')
{
if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/' || str[i] == '(' || str[i] == ')')
{
if (i > 0)
{
if (str[i] == '+' || str[i] == '-')
{
if (!isEmpty(Sign_s) && (getTop(Sign_s) == '*' || getTop(Sign_s) == '/'))
{
char *r_c = (char *)malloc(sizeof(char));
pop(&Num_s, r_c);
int r = strtoul(r_c, NULL, 10);
free(r_c);
char *l_c = (char *)malloc(sizeof(char));
pop(&Num_s, l_c);
int l = strtoul(l_c, NULL, 10);
free(l_c);
switch (getTop(Sign_s))
{
case '*':
snprintf(buf, 2, "%d", l * r);
push(&Num_s, buf[0]);
break;
case '/':
snprintf(buf, 2, "%d", l / r);
push(&Num_s, buf[0]);
break;
default:
break;
}
}
else
{
push(&Sign_s, str[i]);
}
}
if (str[i] == '*' || str[i] == '/')
{
char *l_c = (char *)malloc(sizeof(char));
pop(&Num_s, l_c);
int l = strtoul(l_c, NULL, 10);
free(l_c);
char *r_c = (char *)malloc(sizeof(char));
r_c = &str[i + 1];
int r = strtoul(r_c, NULL, 10);
switch (str[i])
{
case '*':
snprintf(buf, 2, "%d", l * r);
push(&Num_s, buf[0]);
i++;
break;
case '/':
snprintf(buf, 2, "%d", l / r);
push(&Num_s, buf[0]);
i++;
break;
default:
break;
}
}
}
}
else
{
push(&Num_s, str[i]);
}
i++;
}
while (!isEmpty(Sign_s))
{
char *r_c = (char *)malloc(sizeof(char));
int l, r;
char sign;
pop(&Num_s, r_c);
r = strtoul(r_c, NULL, 10);
free(r_c);
char *l_c = (char *)malloc(sizeof(char));
pop(&Num_s, l_c);
l = strtoul(l_c, NULL, 10);
free(l_c);
pop(&Sign_s, &sign);
switch (sign)
{
case '+':
snprintf(buf, 2, "%d", l + r);
push(&Num_s, buf[0]);
break;
case '-':
snprintf(buf, 2, "%d", l - r);
push(&Num_s, buf[0]);
break;
case '*':
snprintf(buf, 2, "%d", l * r);
push(&Num_s, buf[0]);
break;
case '/':
snprintf(buf, 2, "%d", l / r);
push(&Num_s, buf[0]);
break;
default:
break;
}
}
printf("%c\n", getTop(Num_s));
}
int main()
{
Stack Num_s;
Stack Sign_s;
char str[] = "3+9-4*2";
expr(str, Num_s, Sign_s);
}