中缀转后缀表达式(C语言实现)

实现效果
效果

源码

#include<stdio.h>
#include<string.h>
//创建栈 
typedef struct node
{
  char s[1000];
  int top;
}Stack;
//判断符号的函数 
int weight(char ch, int flag)
{
  if(ch=='+'||ch=='-') return 1;
  if(ch=='*'||ch=='/') return 2;
  if(ch=='('&&flag==1) return 0;
  if(ch=='('&&flag==0) return 3;
}
//准换函数 
void transform(char str[])
{
  Stack a;
  a.top=-1;
  int i,f=0,m=strlen(str);
  for(i=0;i<m;i++)
  {
   if(str[i]>='A'&&str[i]<'Z')		//遍历 
   {
     printf("%c",str[i]);
   }
   else
   {
     if(a.top==-1)
     {
       a.s[++a.top]=str[i];
       continue;
     }
     
     if(str[i]==')')
     {
       while(a.top!=-1&&a.s[a.top]!='(')       // 每次进行出栈操作时都要判断栈是否为空,且判断在操作之前。
            printf("%c",a.s[a.top--]);
       --a.top;
       continue;
     }
     
     if(weight(str[i],0)>weight(a.s[a.top],1))
     {
       a.s[++a.top]=str[i];
       continue;
     }
     
     while(a.top!=-1&&weight(str[i],0)<=weight(a.s[a.top],1))   //每次进行出栈操作时都要判断栈是否为空,
     {                                             				//且判断在操作之前。
       printf("%c",a.s[a.top]);          						// 用while循环为不用if语句来比较新读入的操作符与栈顶操作的的权值大小,
       --a.top;                   								// 是因为当新读入的操作符的权值小于栈顶操作符的权值时,也可能小于栈顶
       f=1;                       								// 下一 个操作符的权值
     }
     
     if(f==1)
     {
        a.s[++a.top]=str[i];
        f=0;
     }
   }
  }
  while(a.top!=-1)
  {
    printf("%c",a.s[a.top--]);
  }
}

int main()
{
  char str[310];
  gets(str);
  transform(str);
  return 0;
}


  • 3
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值