1 #include<stdio.h> 2 #include<stdlib.h> 3 const int maxn=1000+5; 4 typedef struct{ 5 int top; 6 int a[maxn]; 7 }opn; 8 typedef struct{ 9 int top; 10 char a[maxn]; 11 }opt; 12 void opn_init(opn *s){ 13 s->top=-1; 14 } 15 void opt_init(opt *s){ 16 s->top=-1; 17 } 18 void opn_push(int x,opn *s){ 19 s->top++; 20 s->a[s->top]=x; 21 } 22 void opt_push(char x,opt *s){ 23 s->top++; 24 s->a[s->top]=x; 25 } 26 void opn_pop(opn *s){ 27 s->top--; 28 } 29 void opt_pop(opt *s){ 30 s->top--; 31 } 32 int opn_top(opn *s){ 33 return s->a[s->top]; 34 } 35 char opt_top(opt *s){ 36 return s->a[s->top]; 37 } 38 int isop(char c) 39 { 40 if (c == ‘+‘ || c == ‘-‘ || c == ‘*‘ || c == ‘/‘ || c == ‘(‘ || c == ‘)‘||c==‘#‘) 41 return 1; 42 else return 0; 43 } 44 char pro(char s,char c) 45 { 46 switch (s){ 47 case(‘+‘): 48 case(‘-‘): 49 if (c == ‘+‘ || c == ‘-‘)return ‘>‘; 50 else if (c == ‘*‘ || c == ‘/‘)return ‘<‘; 51 else if (c == ‘(‘)return ‘<‘; 52 else if (c == ‘)‘)return ‘>‘; 53 else return ‘>‘; 54 break; 55 56 case(‘*‘): 57 case(‘/‘): 58 if (c == ‘+‘ || c == ‘-‘)return ‘>‘; 59 else if (c == ‘*‘ || c == ‘/‘)return ‘>‘; 60 else if (c == ‘(‘)return ‘<‘; 61 else if (c == ‘)‘)return ‘>‘; 62 else return ‘>‘; 63 break; 64 case(‘(‘): 65 if (c == ‘)‘)return ‘=‘; 66 else return ‘<‘; 67 case(‘)‘) : 68 return ‘>‘; 69 case(‘#‘): 70 if (c == ‘#‘)return ‘=‘; 71 else return ‘<‘; 72 } 73 } 74 int oper(int a, char op, int b) 75 { 76 if (op == ‘+‘)return a + b; 77 else if (op == ‘-‘)return a - b; 78 else if (op == ‘*‘)return a*b; 79 else if (op == ‘/‘)return a / b; 80 } 81 int main() 82 { 83 char ch,op; 84 int i,a,b,res; 85 opn p1; 86 opt p2; 87 opn_init(&p1); 88 opt_init(&p2); 89 ch = getchar(); 90 opt_push(‘#‘,&p2); 91 while (ch != ‘#‘||opt_top(&p2) != ‘#‘) 92 { 93 if (!isop(ch)) 94 { 95 i = atoi(&ch); 96 ch = getchar(); 97 while (!isop(ch)) 98 { 99 i = i * 10 + atoi(&ch); 100 ch = getchar(); 101 } 102 opn_push(i,&p1); 103 } 104 else 105 { 106 switch (pro(opt_top(&p2), ch)) 107 { 108 case(‘<‘) : 109 opt_push(ch,&p2); 110 ch = getchar(); 111 break; 112 113 case(‘=‘) : 114 opt_pop(&p2); 115 ch = getchar(); 116 break; 117 118 case(‘>‘) : 119 op = opt_top(&p2); 120 opt_pop(&p2); 121 b = opn_top(&p1); 122 opn_pop(&p1); 123 a = opn_top(&p1); 124 opn_pop(&p1); 125 res=oper(a, op, b); 126 opn_push(res,&p1); 127 break; 128 } 129 } 130 } 131 printf("%d\n", opn_top(&p1)); 132 system("pause"); 133 return 0; 134 }
时间: 2024-12-28 08:27:58