数据结构实验之栈二:一般算术表达式转换成后缀式
题目描述
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
输入
输入一个算术表达式,以‘#’字符作为结束标志。
输出
输出该表达式转换所得到的后缀式。
示例输入
a*b+(c-d/e)*f#
示例输出
ab*cde/-f*+
#include <bits/stdc++.h>
using namespace std;
stack<int>Q; //建立栈
void Transform(char str[])
{
int i;
for(i=0; str[i]!='#'; i++)
{
if(str[i]>='a'&&str[i]<='z') //如果是字母的话就直接输出
{
cout<<str[i];
}
else if(str[i]=='(') //遇到左括号,进栈
{
Q.push(str[i]);
}
else if(str[i]==')') //遇到右括号时,如果栈顶不是左括号,则将左括号上面的数字或者符号全部输出
{
while(Q.top()!='(')
{
printf("%c",Q.top());
Q.pop();
}
Q.pop(); //删除左括号
}
else if(str[i]=='+'||str[i]=='-')
{
while(!Q.empty()&&Q.top()!='(') //运算级较低,满足条件时输出
{
printf("%c",Q.top());
Q.pop();
}
Q.push(str[i]); //如果不是以上符号的话,就進入栈中存储
}
else if(str[i]=='*'||str[i]=='/')
{
while(!Q.empty()&&Q.top()!='('&&(Q.top()=='*'||Q.top()=='/'))
{
printf("%c",Q.top());
Q.pop();
}
Q.push(str[i]);
}
}
while(!Q.empty()) //输出所有的元素
{
printf("%c",Q.top());
Q.pop();
}
}
int main()
{
char str1[110];
scanf("%s",str1);
Transform(str1);
cout<<endl;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
stack<int>Q; //建立栈
void Transform(char str[])
{
int i;
for(i=0; str[i]!='#'; i++)
{
if(str[i]>='a'&&str[i]<='z') //如果是字母的话就直接输出
{
cout<<str[i];
}
else if(str[i]=='(') //遇到左括号,进栈
{
Q.push(str[i]);
}
else if(str[i]==')') //遇到右括号时,如果栈顶不是左括号,则将左括号上面的数字或者符号全部输出
{
while(Q.top()!='(')
{
printf("%c",Q.top());
Q.pop();
}
Q.pop(); //删除左括号
}
else if(str[i]=='+'||str[i]=='-')
{
while(!Q.empty()&&Q.top()!='(') //运算级较低,满足条件时输出
{
printf("%c",Q.top());
Q.pop();
}
Q.push(str[i]); //如果不是以上符号的话,就進入栈中存储
}
else if(str[i]=='*'||str[i]=='/')
{
while(!Q.empty()&&Q.top()!='('&&(Q.top()=='*'||Q.top()=='/'))
{
printf("%c",Q.top());
Q.pop();
}
Q.push(str[i]);
}
}
while(!Q.empty()) //输出所有的元素
{
printf("%c",Q.top());
Q.pop();
}
}
int main()
{
char str1[110];
scanf("%s",str1);
Transform(str1);
cout<<endl;
return 0;
}