关于中缀表达式转后缀表达式
关于中缀表达式转后缀表达式,这个需要利用栈来实现
#include<bits/stdc++.h>
using namespace std ;
typedef struct Bi_Node{
int data ;
Bi_Node *lchild , *rchild ;
}Bi_Node, * Bi_Tree ;
stack<char>s ;
queue<char >q ;
void change(string str ){
for(int i = 0 ;i< str.length() ;i ++ ){
if(str[i] >= 'a' && str[i] <= 'z'){
q.push(str[i]);
}else if(str[i]=='('){//直接入栈
s.push(str[i]);
}else if(str[i] == '+' || str[i] == '-'){
while (!s.empty()&&s.top()!= '('){//栈顶为*/,将栈内元素出栈
q.push(s.top());
s.pop();
}
s.push(str[i]);//再将当前的入栈
}else if(str[i] =='*' || str[i] == '/'){
if(s.top()== '+' || s.top()== '-' || s.top()=='(' || s.empty()){//栈顶优先级低
s.push(str[i]);
}else {//先出栈再入栈
q.push(s.top());
s.pop();
s.push(str[i]);
}
}else {//为),出栈,直到(
while (s.top()!='('&&!s.empty()){
q.push(s.top());
s.pop() ;
}
if(s.top() == ')'){//()是不入队的
s.pop() ;
}
}
}
while (!s.empty()){//栈中可能有遗留
q.push(s.top());
s.pop() ;
}
}
int main(){
string str ;
cout << "请输入字符串(为包含字母、+、-、*、/、左右括号):"<<endl;
getline(cin,str);//从屏幕输入一行字符串存入str中;
change(str);
cout << "后缀表达式为:"<<endl;
while(q.size()>1){
cout << q.front() << " ";
q.pop();
}
cout << q.front() << endl;
system("pause");
return 0;
return 0 ;
}