
1 #include<stdio.h> 2 #define MaxSize 20 3 typedef struct{ 4 char element[MaxSize]; 5 int top; 6 }SeqStack; 7 void InitStack(SeqStack*p)//初始化 8 { 9 p->top=-1; 10 } 11 void PushStack(char e,SeqStack*p)//压栈 12 { 13 if(p->top!=MaxSize-1){ 14 p->top++; 15 p->element[p->top]=e;} 16 } 17 char PopStack(SeqStack*p)//出栈 18 { 19 char x; 20 if(p->top!=-1){ 21 x=p->element[p->top]; 22 p->top--;} 23 return x; 24 } 25 int Compare(char left,char right)//比较函数 26 { 27 int flag; 28 switch(left) 29 { 30 case '+': 31 { 32 if(right=='-'||right==')'||right=='\n')flag=0; 33 else if(right=='*'||right=='/'||right=='(')flag=2; 34 break; 35 } 36 case '-': 37 { 38 if(right=='+'||right==')'||right=='\n')flag=0; 39 else if(right=='*'||right=='/'||right=='(')flag=2; 40 break; 41 } 42 case '*': 43 { 44 if(right=='+'||right=='-'||right=='/'||right==')'||right=='\n')flag=0; 45 else if(right=='(')flag=2; 46 break; 47 } 48 case '/': 49 { 50 if(right=='+'||right=='-'||right=='*'||right==')'||right=='\n')flag=0; 51 else if(right=='(')flag=2; 52 break; 53 } 54 case '(': 55 { 56 if(right==')')flag=1; 57 else flag=2; 58 break; 59 }//注:只要right为')'就会不停往前Execute直至遇到'(',并最后读取下一个数据 。故')'不会被储存到b中 60 case '\n':flag=3;break; 61 62 } 63 return flag; 64 } 65 void Conversation(SeqStack*a,SeqStack*b)//a存储后缀表达式,b暂时存储运算符 66 { 67 char e,oper; 68 scanf("%c",&e); 69 while(e!='\n'||b->top!=-1)//!!不要将||写成&& 70 { 71 if(e!='+'&&e!='-'&&e!='*'&&e!='/'&&e!='('&&e!=')'&&e!='\n')PushStack(e,a),scanf("%c",&e); 72 /* 读取到运算数则存入栈a,并继续读取 */ 73 else if(b->top==-1||Compare(b->element[b->top],e)==2)PushStack(e,b),scanf("%c",&e); 74 /* 读取到运算符,当b栈为空或当前运算符优先级大于b栈首,入栈b,并继续读取 */ 75 else if(Compare(b->element[b->top],e)==1)PopStack(b),scanf("%c",&e); 76 /* 读取到')',当')'遇到'(',将'('弹出栈b,并继续读取 */ 77 else if(Compare(b->element[b->top],e)==0) 78 { 79 oper=PopStack(b); 80 PushStack(oper,a); 81 } 82 /* 读取到运算符,当运算符优先级低于b栈首,弹出b栈首并存入到a中,继续比较当前运算符 */ 83 } 84 } 85 int main() 86 { 87 SeqStack A,B; 88 SeqStack*a,*b; 89 a=&A,b=&B; 90 InitStack(a),InitStack(b); 91 Conversation(a,b); 92 a->top++,a->element[a->top]='\n'; 93 for(int i=0;a->element[i]!='\n';i++)printf("%c",a->element[i]); 94 return 0; 95 }