1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<stdbool.h> 4 #include<ctype.h> 5 #define MAXOP 100 6 typedef struct SNode{ 7 char *Data; 8 int Top; 9 int Maxsize; 10 }Stack; 11 12 Stack *CreateStack(int Maxsize) 13 { 14 Stack *S; 15 S=(Stack *)malloc(sizeof(struct SNode)); 16 S->Top=-1; 17 S->Data=(char *)malloc(Maxsize * sizeof(char)); 18 S->Maxsize=Maxsize; 19 return S; 20 } 21 22 bool IsFull(Stack *S) 23 { 24 return (S->Top==S->Maxsize-1); 25 } 26 27 void Push(Stack *S,char op) 28 { 29 if(!IsFull(S)) 30 { 31 S->Data[++(S->Top)]=op; 32 } 33 } 34 35 bool IsEmpty(Stack *S) 36 { 37 return (S->Top==-1); 38 } 39 40 char Pop(Stack *S) 41 { 42 char op; 43 if (!IsEmpty(S)) 44 { 45 op=S->Data[(S->Top)--]; 46 } 47 return op; 48 } 49 char Top(Stack *S) 50 { 51 char op; 52 if (!IsEmpty(S)) 53 { 54 op=S->Data[(S->Top)]; 55 } 56 return op; 57 } 58 59 typedef enum {num,opr,end}Type; 60 61 Type GetOp(char *Expr,int *start,char *str) 62 { 63 int i=0; 64 while ((str[0]=Expr[(*start)++])==‘ ‘); 65 while (str[i]!=‘ ‘ && str[i]!=‘\0‘) 66 { 67 str[++i]=Expr[(*start)++]; 68 } 69 if (str[i]==‘\0‘)(*start)--; 70 str[i]=‘\0‘; 71 72 if (i==0) return end; 73 else if (isdigit(str[0])||isdigit(str[1])) return num; 74 else return opr; 75 } 76 77 int Prior(char op) 78 { 79 switch (op) 80 { 81 case ‘*‘: 82 case ‘/‘: return 2; 83 case ‘+‘: 84 case ‘-‘: return 1; 85 case ‘(‘: return 0; 86 } 87 } 88 89 void PrintPostfixExp(char *Expr) 90 { 91 int start=0; 92 Type T; 93 char str[MAXOP]; 94 char op1,op2; 95 Stack *S; 96 S=CreateStack(MAXOP); 97 while((T=GetOp(Expr,&start,str))!=end) 98 { 99 if (T==num)printf("%s ",str); 100 else 101 { 102 switch(str[0]) 103 { 104 case ‘(‘:Push(S,str[0]);break; 105 case ‘)‘: 106 { 107 while(Top(S)!=‘(‘)printf("%c ",Pop(S)); 108 Pop(S); 109 break; 110 } 111 case ‘+‘: 112 case ‘-‘: 113 case ‘*‘: 114 case ‘/‘: 115 { 116 if (IsEmpty(S)){Push(S,str[0]);break;} 117 else 118 { 119 op1=Top(S); 120 if (Prior(str[0])<=Prior(op1))printf("%c ",Pop(S)); 121 Push(S,str[0]); 122 } 123 break; 124 } 125 126 } 127 } 128 } 129 while(!IsEmpty(S))printf("%c ",Pop(S)); 130 } 131 132 int main() 133 { 134 char Expr[MAXOP]; 135 gets(Expr); 136 PrintPostfixExp(Expr); 137 return 0; 138 }
时间: 2024-10-04 18:02:07