#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MaxSize 100
int priority(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '(':
return 0;
default:
return -1;
}
}
char* infix_to_postfix(char* infix) {
int len = strlen(infix);
char* postfix = (char*)malloc((len + 1) * sizeof(char)); // 分配足够的空间
memset(postfix, 0, (len + 1) * sizeof(char)); // 初始化为空字符串
char stack[len]; // 栈
int top = -1; // 栈顶指针
for (int i = 0; i < len; i++) {
char c = infix[i];
if (c >= '0' && c <= '9') { // 数字
int j = i + 1;
while (infix[j] >= '0' && infix[j] <= '9') j++;
//char *strncat(char *dest, const char *src, size_t n)
//把 src 所指向的字符串追加到 dest 所指向的字符串的结尾,直到 n 字符长度为止。
strncat(postfix, infix + i, j - i);
//char *strcat(char *dest, const char *src)
//把 src 所指向的字符串追加到 dest 所指向的字符串的结尾。
strcat(postfix, " ");
i = j - 1;//after i++
}
else if (c == '(') { // 左括号
stack[++top] = c;
}
else if (c == ')') { // 右括号
while (top >= 0 && stack[top] != '(') {
postfix[strlen(postfix) + 1] = '\0';
postfix[strlen(postfix)] = stack[top--];
strcat(postfix, " ");
}
if (top >= 0 && stack[top] == '(') {
top--;
}
}
else if (c == '+' || c == '-' || c == '*' || c == '/') { // 运算符
while (top >= 0 && priority(stack[top]) >= priority(c)) {
postfix[strlen(postfix) + 1] = '\0';
postfix[strlen(postfix)] = stack[top--];
strcat(postfix, " ");
}
stack[++top] = c;
}
}
while (top >= 0) { // 弹出栈中剩余的运算符
postfix[strlen(postfix) + 1] = '\0';
postfix[strlen(postfix)] = stack[top--];
strcat(postfix, " ");
}
return postfix;
}
void evalPf(char* str){
int len = strlen(str);
int stack[len + 1]; // 栈
int top = -1; // 栈顶指针
int i = 0,op1,op2,res,sum;
while(str[i] != '\0'){
if (str[i] >= '0' && str[i] <= '9'){
sum = 0;
sum = str[i] - '0';
i++;
while (str[i] >= '0' && str[i] <= '9')
{
sum = sum * 10 + str[i] - '0';
i++;
}
stack[++top] = sum;
}
if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/'){
op2 = stack[top--];
op1 = stack[top--];
if (str[i] == '+')
stack[++top] = op1 + op2;
else if (str[i] == '-')
stack[++top] = op1 - op2;
else if (str[i] == '*')
stack[++top] = op1 * op2;
else if (str[i] == '/')
stack[++top] = op1 / op2;
else
printf("error\n");
}
i++;
}
printf("%d\n",stack[top--]);
}
int main(){
char infix[MaxSize];//1+2-2*(4/2+1)-1
scanf("%s",infix);
char* postfix = infix_to_postfix(infix);
printf("中缀表达式:%s\n", infix);
printf("后缀表达式:%s\n", postfix);
printf("%s=", infix);
evalPf(postfix);
free(postfix);
return 0;
}