数据结构:中缀表达式转后缀表达式
#include <stdio.h> #include "SqStack2.h" #define STACKTYPE SqStack #define BOOL int #define TRUE 1 #define FALSE 0 BOOL isnumeric(char c) { return (c >= '0' && c <= '9') ? TRUE : FALSE; } int lv(char c) { int wt[] = {3,0,2,1,-1,1,-1,2}; return wt[c - '(']; } void expr() { char ex[] = "10+(3+4)*(12-6)"; int i,n; BOOL isNumber = FALSE;//上一个字符是否是数字,连续两个数字要合并 STACKTYPE st; init(&st); for (i = 0; ex[i] != '\0'; i++) { if (isnumeric(ex[i])){ if (isNumber == FALSE) printf(" "); printf("%d", ex[i]-'0'); isNumber = TRUE; } else { isNumber = FALSE; if (ex[i] == ')'){//如果是右括号,则匹配栈中第一个左括号 n = ' '; do { if (n != ' ') printf(" %c", n); } while (pop(&st, &n)==OK && n != '('); } else if (ex[i] == '(') {//左括号直接入栈 push(&st, ex[i]); } else {//其他运算符,输出栈中所有优先度更高的运算符 while (getTop(st, &n) == OK && n != '(' && lv(n) >= lv(ex[i])) pop(&st, &n); push(&st, ex[i]); } } } while (pop(&st, &n) == OK) printf(" %c", n); printf("\n"); destroy(&st); } main() { expr(); }