CPP

C++逆波兰式的实现

#include <stdio.h>
#include <string.h>
#define elemtype  char
   const  int maxsize=50;
   struct stack
   {
     elemtype s[maxsize];
     int top;
  
     void setnull()//初始化
  {   top=0;  }
     void push( elemtype  x)//将元素压入栈
  { if(top>=maxsize-1)
   printf("栈满\n");
  top++;
  s[top]=x;
  }
  elemtype pop()//将元素出栈
  { elemtype x;
  if(top<0)
   printf("栈空\n");
  x=top;
  top++;
  return x;
  }
  elemtype gettop()//寻找栈顶元素
  { elemtype  x;
   if(top!=x)
      printf("栈空\n");
   x=top-1;
      return x;
  }
  elemtype pre(elemtype  x1, elemtype  x2)//判断栈顶元素与a数组中的第一个元素的优先级
  { elemtype result='<';
  elemtype sting[2];
  sting[0]=x2;
  sting[1]='\0';
  if(((x1=='+'||x1=='-')&&(strstr("+-)#",sting)!=NULL))||((x1=='*'||x1=='/')&&strstr("+-*/)#",sting)!=NULL)||(x1==')'&&strstr("+-*/)#",sting)!=NULL))
   result='>';
  else
   if(x1=='('&&x2==')'||x1=='#'&&x2=='#')
      result='=';
   else
   if(x1==')'&&x2=='('||x1=='#'&&x2==')')
     result='=';
  return result;
  }
   };
   int main()
   {   stack s;
       int i=0;    
       elemtype a[maxsize],ch,b;
       printf("本程序实现:将中缀表达式变为后缀表达式 \n");      
     printf("请输入中缀表达式并以'#'作为结束:\n");
       gets(a);
       printf("转换成的后缀表达式为:\n");
    s.setnull();
    s.push('#');
    ch=a;
   while(ch!='#'||s.gettop()!='#')
{ if(ch!='+'&&ch!='-'&&ch!='*'&&ch!='/'&&ch!='('&&ch!=')'&&ch!='#')
  { printf("%c",ch);
  ch=a[++i];
  if(ch=='\0')
   break;
  }
  else
     switch(s.pre(s.gettop(),ch))
{ case  '<' :   s.push(ch);  ch=a[++i];
     break;
   case  '=' :   s.pop();  ch=a[++i];
     break;
      case  '>' :   b=s.pop();  printf("%c",b);
     break;
}
}    
     printf("\n");
    return 0;
   }