SzNOI c003 中缀表达式转后缀表达式

个人觉得我写的应该是目前网上写的版本比较简单的了。。。这也是我开博客的原因,尽量写出简单的代码,一方面可以巩固自己,一方面也能方便别人

中缀表达式转化为后缀表达式是通过栈实现

思路是,写两个函数,分别是算术操作符的优先级,这个想法在数据结构 :用面向对象方法与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 ;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值