中缀表达式转化为后缀表达式

习自

#include <bits/stdc++.h>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
#define LL long long
#define ll long long
#define ULL unsigned long long
#define ls rt<<1
#define rs rt<<1|1
#define MS 100009
#define INF 1e18
#define mod 998244353
#define Pi acos(-1.0)
#define Pair pair<LL,LL>
#define eps 1e-9

LL n,m,k;
char s[MS]; // 字符串读入中缀表达式 
LL hs; 		// 中缀表达式的len  
stack<LL> fu;
LL prfu[300]; 	// 定义 + - * / ^ 优先级 
LL hz[MS],thz; 	// 存放后缀表达式 ,若第i位为字符则 vf[i] = 1; 
LL vf[MS]; 		// 标记 1 为符 ;

void init_prfu(){ // 定义 + - * / ^ 优先级 
	prfu['('] = prfu[')'] = 0;
	prfu['+'] = prfu['-'] = 1;
	prfu['*'] = prfu['/'] = 2;
	prfu['^'] = 3;
}

void s_hz(){ // 得到 后缀表达式 hz[1...thz] ,其中字符以数字表示 ,vf[i]=1 表示 hz[i] 为字符 
	hs = strlen(s);
	LL num = 0;
	LL flnum = 0;
	for(int i=0;i<hs;i++){
		if('0' <= s[i] && s[i] <= '9'){
			flnum = 1;
			num = num*10+(s[i]-'0');
			continue;
		} 
		else if(flnum) hz[++thz] = num ,num = flnum = 0;
		if(fu.empty()){
			fu.push(s[i]);
			continue;
		} 
		if(s[i] == '(') fu.push(s[i]);
		else if(s[i] == ')'){
			while(fu.top() != '('){
				hz[++thz] = fu.top();
				vf[thz] = 1;
				fu.pop();
			}
			fu.pop();
		}
		else{
			while(!fu.empty() && prfu[s[i]] <= prfu[fu.top()]){
				hz[++thz] = fu.top();
				vf[thz] = 1;
				fu.pop();
			}
			fu.push(s[i]);
		}
	}
	if(flnum) hz[++thz] = num ,num = flnum = 0;
	while(!fu.empty()){
		hz[++thz] = fu.top();
		vf[thz] = 1;
		fu.pop();
	}
}

int main(){
	ios::sync_with_stdio(false);
	init_prfu();
	cin >> s;
	s_hz();
	
	for(int i=1;i<=thz;i++){
		if(vf[i]) printf("%c ",hz[i]);
		else printf("%lld ",hz[i]);
	}
	printf("\n");


	return 0;
}

/*
88-(333+22*6)/55+4 

88 333 22 6 * + 55 / - 4 + 
*/ 
posted @ 2021-03-09 16:51  棉被sunlie  阅读(118)  评论(0)    收藏  举报