nyoj467 中缀式变后缀式

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #define N 1010
  4 //字符栈的操作
  5 typedef struct
  6 {
  7   char *base;
  8   char *top;
  9 }SqStack;
 10 int InitStack(SqStack &S)
 11 {
 12   S.base=(char *)malloc(N*sizeof(char));
 13   if(!S.base)  exit(1);
 14   S.top=S.base;
 15   return 1;
 16 }
 17 int StackEmpty(SqStack &S)
 18 {
 19   if(S.top==S.base)
 20   return 1;
 21   return 0;
 22 }
 23 int GetTop(SqStack S,char &e)
 24 {
 25     if(S.top==S.base)  return 0;
 26     e=*(S.top-1);
 27     return 1;
 28 }
 29 int Push(SqStack &S,char e)
 30 {
 31   *S.top++=e;
 32   return 1;
 33 }
 34 int Pop(SqStack &S,char &e)
 35 {
 36   if(S.top==S.base)  return 0;
 37   e=*--S.top;
 38   return 1;
 39 }
 40 //转化的操作过程
 41 static int i;
 42 int Pass(char *s,char c)
 43 {
 44     s[i]=c;
 45     i++;
 46     return 1;
 47 }
 48 int level(char c,int k)
 49 {
 50     switch(c)
 51     {
 52         case '=': return 1;
 53         case ')': return k?2:5;
 54         case '+':
 55         case '-': return 3;
 56         case '*':
 57         case '/': return 4;
 58         case '(': return k?5:2;
 59         default : return 0;
 60     }
 61 }
 62 int Precede(char c1,char c2)
 63 {
 64     int k=(c1=='('&&c2=='=')||(c1=='='&&c2==')')||(c1==')'&&c2=='(');
 65     if(!k)
 66     {
 67         if(level(c1,0)<level(c2,1)||c1=='='&&c2=='=') return 0;
 68         return 1;
 69     }
 70     return 0;
 71 }
 72 int Converse(char *s)
 73 {
 74     SqStack OPTR;
 75     char ch,x,c=getchar();
 76     InitStack(OPTR); Push(OPTR,'=');
 77     while(!StackEmpty(OPTR))
 78     {
 79         if(!level(c,1))
 80             Pass(s,c);
 81         else
 82         switch(c)
 83         {
 84             case '(': Push(OPTR,c);break;
 85             case ')': Pop(OPTR,ch);while(ch!='('){Pass(s,ch);Pop(OPTR,ch);}break;
 86             default :
 87                       while(GetTop(OPTR,ch)&&Precede(ch,c))
 88                       {
 89                           Pass(s,ch);Pop(OPTR,ch);
 90                       }
 91                       if(c!='=')
 92                       Push(OPTR,c);
 93                       break;
 94         }
 95         if(c!='=')
 96         {
 97             x=c;c=getchar();
 98             if(!level(x,1)&&level(c,1))
 99             Pass(s,' ');
100         }
101         else
102             Pop(OPTR,ch);
103     }
104     s[i]='\0';
105     return 1;
106 }
107 //主函数
108 int main()
109 {
110     char s[1010];
111     int j,n;
112     scanf("%d",&n);
113     while(n--){
114         getchar();
115         i=0;
116         Converse(s);
117         for(j=0;s[j];++j){
118             putchar(s[j]);
119             if(level(s[j],0)) putchar(' ');
120         }
121         printf("=\n");  
122     }
123     //system("pause");
124     return 0;
125 }

 

posted on 2012-08-02 08:39  小花熊  阅读(317)  评论(0编辑  收藏  举报

导航