中缀->前缀,该对必关!
查看原帖
中缀->前缀,该对必关!
1243618
Jokersheng楼主2024/9/15 22:30

没有输出求助

#include <bits/stdc++.h>
using namespace std;

//f前缀,m中缀,b后缀 

char m;

string s;
bool p,q;

int main(){
	stack <char> s1;
	stack <char> s2;
	cin>>m;
	if(m=='f'){
		cout<<"前缀表达式:";
		cin>>s;
	}else if(m=='m'){
		cout<<"中缀表达式:";
		cin>>s; 
		int lens=s.length();
		//前缀 
		for(int i=lens-1;i>=0;i--){
			if((s[i]>='0'&&s[i]<='9')||s[i]==')'){
				s2.push(s[i]);
			}else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'||s[i]=='^'){
				if(s1.top()=='+'||s1.top()=='-'){
					q=0;
				}else{
					q=1;
				}
				if(s[i]=='+'||s[i]=='-'){
					p=0;
				}else{
					p=1;
				}
				while(true){
					if(s2.empty()||s2.top()==')'){
						s1.push(s[i]);
						break; 
					}else if(p>=q){
						s1.push(s[i]);
						break;
					}else{
						s2.push(s1.top());
						s1.pop();
					}
				}
			}else{
				while(s1.top()!=')'){
					s2.push(s1.top());
					s1.pop();
				}
				s1.pop();
			}
		}
		cout<<"前缀表达式:"; 
		while(s2.size()>0){
			cout<<s2.top();
			s2.pop();
		}
	}else{
		cout<<"后缀表达式:";
	}
}
2024/9/15 22:30
加载中...