中缀表达式转后缀表达式
中缀表达式就是我们常见的算术表达式,比如:23+4(3+5)+10/2,运算符在运算数之间,而后缀表达式就是比如:59684/-3+#,运算符在运算数的后面,所以要把中缀表达式转后缀表达式,用栈来实现。
因为*/的优先级大于±,所以如下所示:
1.如果是操作数,直接输出,即为后缀表达式的。
2.如果栈为空,就代表没有运算符,所以遇到运算符就压入栈中。
3.如果是( ,直接压入栈中。
4.如果是 ),就开始出栈,直到遇到( ,但( 不输出,只弹出。
5.如果是+ - ,因为±的优先级比 乘除 小,所以只有遇到优先级最小的(,才能入栈,所以就出栈,直到遇到(,再把现在的压进去栈。
6.如果是乘除,优先级高,所以只有遇到栈顶同样是乘除,才可以弹出,然后把现在的压进去栈。
7.最后把栈中的都弹出来。
总结一下,就是( 压入栈中优先级降为最小,直到遇到),才可出栈,其他运算符,如果栈顶的优先级比自己大或跟自己相同,弹出栈顶,直到栈顶的优先级小于自己,再把自己压进去。最后当所有操作数都走完,再把栈中的都弹出来。
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[1001],stack[1001];
ios::sync_with_stdio(false);
scanf("%s",s);
int top=0;
for(int i=0;s[i]!='#';i++)
{
if(s[i]>='a'&&s[i]<='z')
{
cout<<s[i];
}
else if(s[i]=='(')
{
stack[++top]=s[i];
}
else if(s[i]==')')
{
while(stack[top]!='(')
{
cout<<stack[top];
top--;
}
top--;
}
else if(s[i]=='+'||s[i]=='-')
{
while(top!=0&&stack[top]!='(')
{
cout<<stack[top];
top--;
}
stack[++top]=s[i];
}
else if(s[i]=='*'||s[i]=='/')
{
while(top!=0&&stack[top]!='('&&(stack[top]=='*'||stack[top]=='/'))
{
cout<<stack[top];
top--;
}
stack[++top]=s[i];
}
}
while(top!=0)
{
cout<<stack[top];
top--;
}
return 0;
}
算术表达式转前缀,中缀,后缀
#include<bits/stdc++.h>
using namespace std;
int cmp(char x)
{
if(x=='+'||x=='-') return 1;
else if(x=='*'||x=='/') return 2;
else if(x=='('||x==')') return 3;
}
void work1(string ch)
{
char a[1200];
int k=0;
for(int i=ch.size()-2;i>=0;i--){
a[k++]=ch[i];
}
stack<char>s1;
stack<char>s2;
for(int i=0;i<k;i++){
if(a[i]>='a'&&a[i]<='z'){
s1.push(a[i]);
}
else{
if(a[i]==')')
s2.push(a[i]);
else if(a[i]=='('){
while(s2.top()!=')'){
char t=s2.top();
s2.pop();
s1.push(t);
}
s2.pop();
}
else{
if(!s2.empty()&&cmp(s2.top())>cmp(a[i])){
if(s2.top()==')')
s2.push(a[i]);
else{
char t=s2.top();
s2.pop();
s1.push(t);
s2.push(a[i]);
}
}
else{
s2.push(a[i]);
}
}
}
}
while(!s2.empty()){
char t=s2.top();
s1.push(t);
s2.pop();
}
while(!s1.empty()){
char t=s1.top();
cout<<t;
s1.pop();
}
cout<<endl;
}
void work2 (string ch)
{
for(int i=0;i<ch.size()-1;i++){
if(ch[i]=='('||ch[i]==')')
continue;
else
cout<<ch[i];
}
cout<<endl;
}
void work3(string ch)
{
char stack[1200];
int top=0;
for(int i=0;ch[i]!='#';i++)
{
if(ch[i]>='a'&&ch[i]<='z')
{
cout<<ch[i];
}
else if(ch[i]=='(')
{
stack[++top]=ch[i];
}
else if(ch[i]==')')
{
while(stack[top]!='(')
{
cout<<stack[top];
top--;
}
top--;
}
else if(ch[i]=='+'||ch[i]=='-')
{
while(top!=0&&stack[top]!='(')
{
cout<<stack[top];
top--;
}
stack[++top]=ch[i];
}
else if(ch[i]=='*'||ch[i]=='/')
{
while(top!=0&&stack[top]!='('&&(stack[top]=='*'||stack[top]=='/'))
{
cout<<stack[top];
top--;
}
stack[++top]=ch[i];
}
}
while(top!=0)
{
cout<<stack[top];
top--;
}
}
int main()
{
ios::sync_with_stdio(false);
string ch;
cin>>ch;
work1(ch);//前缀
work2(ch);//中缀
work3(ch);//后缀
return 0;
}