实现效果
源码
#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;
}