个人觉得我写的应该是目前网上写的版本比较简单的了。。。这也是我开博客的原因,尽量写出简单的代码,一方面可以巩固自己,一方面也能方便别人
中缀表达式转化为后缀表达式是通过栈实现
思路是,写两个函数,分别是算术操作符的优先级,这个想法在数据结构 :用面向对象方法与c++里面这本书有大概提到
isp是栈内优先数,icp是栈外优先数
具体操作 :(我直接引用书本的)
1.操作符栈初始化,将结束符 # 进栈,然后读入中缀表达式的字符流的首字符
2.判断首字符是否是操作符,判断优先级,然后三种操作,具体看代码
3.over
转载注明出处~#include<iostream>
#include<string>
#include<ctype.h>
//isp是栈内优先数 ;
//icp是栈外优先数 ;
using namespace std ;
class Stack {
private :
int top ;
char *elements ;
int maxSize ;
public:
Stack (int sz) {
top = -1 ;
maxSize =sz ;
elements =new char [maxSize] ;
//assert(elements != NULL) ;
}
bool IsEmpty () {
return (top == -1) ?true:false ;
}
void Push (const char &x ) {
elements[++top] = x;
}
bool Pop (char &x ) {
if(IsEmpty () == true ) return false ;
x =elements [top --] ;
return true ;
}
bool getTop (char &x) {
if(IsEmpty () == true ) return false ;
x = elements [top] ;
return true ;
}
};
int isp (char ch) {
if(ch == '#')
return 0 ;
if(ch == '(')
return 1 ;
if(ch == '*' || ch == '/'|| ch == '%' )
return 5 ;
if(ch == '+' || ch == '-')
return 3 ;
if(ch == ')')
return 6 ;
else
return -1 ;
}
int icp (char ch) {
if(ch == '#')
return 0 ;
if(ch == '(')
return 6 ;
if(ch == '*' || ch == '/'|| ch == '%' )
return 4 ;
if(ch == '+' || ch == '-')
return 2 ;
if(ch == ')')
return 1 ;
else
return -1 ;
}
void postfix (string test) {
Stack s (1000) ;
static int i =0;
char ch = '#',ch1,op ;
s.Push (ch ) ;
// test[i++] ;
while (s.IsEmpty() == false && test[i] != '#') {
if(isdigit (test[i]) ) {//if the word is a op word ;
cout <<test[i]<<" " ;
i++ ;
}
else { //the word not a op word but a op number ;
s.getTop (ch1) ;
if(isp(ch1) < icp(test[i]) ) {
s.Push (test[i]) ;
i++ ;
}
else if(isp(ch1) > icp(ch1) ) {
s.Pop(op);
cout<<op<<" " ;
}
else {
s.Pop (op) ;
if(op == '('){
i++ ;
}
}
}
}
}
int main () {
string e ;
cin >>e ;
postfix (e) ;
return 0 ;
}