中缀表达式:普通四则运算
后缀表达式:运算符在数字后面,式子没有括号
中缀变后缀:按照优先级给式子全加上括号,然后把运算符移到对应的括号后面
视频
文章
代码
//算术表达式的求值。算术表达式包括以下运算符: ( ) + - * / 。采用堆栈实现。只能是个位数。
#include<stdio.h>
#include<stdlib.h>
#define SIZE 50
typedef struct stack {
char* elem;
int top;
int base;
}stack;
void initstack(stack& s) {
s.elem = (char*)malloc(SIZE);
if (!s.elem) return;
s.top = s.base = 0;
}
void push(stack& s, char value) {
if (s.top == SIZE) return;
s.elem[s.top++] = value;
}
char pop(stack& s) {
if (s.base == s.top) return NULL;
return s.elem[--s.top];
}
char gettop(stack& s) {
if (s.base == s.top) return NULL;
return s.elem[s.top - 1];
}
void show(stack s) {
for (int i=0;i<s.top;i++) {
printf("%c", s.elem[i]);
}
printf("\n");
}
stack infix_to_suffix(stack& suffix) {
stack char_stack;
initstack(char_stack);
printf("输入算术表达式:");
char top, temp = getchar();
while (temp != '\n') {
if (48 <= temp && temp <= 57)
push(suffix, temp);
else if(temp=='(')
push(char_stack, temp);
else if (temp == ')'){
while (gettop(char_stack) != '(')
push(suffix,pop(char_stack));
pop(char_stack);
}
else {
top = gettop(char_stack);
if ((temp == '+' || temp == '-')&&(top == '*' || top == '/')) {
while (char_stack.base != char_stack.top)
push(suffix, pop(char_stack));
push(char_stack, temp);
}
else
push(char_stack, temp);
}
temp = getchar();
}
while (char_stack.top != char_stack.base)
push(suffix, pop(char_stack));
printf("后缀式为:");
show(suffix);
return suffix;
}
void calc(stack suffix) {
stack calcs;
initstack(calcs);
int pre, post, temp;
for (int i = suffix.base; i <= suffix.top; i++) {
temp = suffix.elem[i];
if (48 <= temp && temp <= 57)
push(calcs, temp - '0'); //易错点:在计算后缀式时是将每个元素都看成char,各函数都是根据char制定;计算数值时数字不能看成字符,否则会变成ascll码的运算
else {
pre = pop(calcs);
post = pop(calcs);
switch (temp){
case '+':push(calcs, post + pre); break;
case '-':push(calcs, post - pre); break;
case '*':push(calcs, post * pre); break;
case '/':push(calcs, post / pre); break;
}
}
}
printf("结果为:%d", calcs.elem[0]);
}
int main() {
stack suffix_stack;
initstack(suffix_stack);
calc(infix_to_suffix(suffix_stack));
}
//9+(3-1)*3+8/2