前綴、中綴、後綴表達式轉換C++

#include <iostream>
#include <stack>
#include <cctype>
using namespace std;

//優先級 
int you(char c){
	if(c=='+'||c=='-')
		return 0;
	else
		return 1;
}

//中綴轉前綴,從後向前掃描,然後翻轉 
void in2pre(char A[], char B[], int n){
	stack<char> sign;//符號棧 
	int j = 0;//B中元素個數 
	for(int i=n-1; i>=0; --i){
		//數字直接入棧 
		if(isdigit(A[i]))
			B[j++] = A[i];
		else if(A[i]==')')
			sign.push(A[i]);
		else if(A[i]=='('){
			while(sign.top()!=')'){
				B[j++] = sign.top();
				sign.pop();
			}
			sign.pop();//刪掉右括號 
		}
		//符號比較優先級 
		else{
			if(sign.empty())
				sign.push(A[i]);
			else{
				//A[i]與棧頂元素比較優先級,直到遇到')'或者棧空 
				while(!sign.empty() && sign.top()!=')' && you(A[i])<you(sign.top())){
					B[j++] = sign.top();
					sign.pop();
				}
				sign.push(A[i]);
			}
		} 
	} 
	//棧中如果還有符號,直接添加到B中就ok 
	while(!sign.empty()){
		B[j++] = sign.top();
		sign.pop();
	}
	//翻轉
	for(int i=0; i<j/2; ++i){
		int t = B[i];
		B[i] = B[j-i-1];
		B[j-i-1] = t;
	} 
} 

//中綴轉後綴 
void in2post(char A[], char B[], int n){
	stack<char> sign;//符號棧 
	int j = 0;//B中元素個數 
	for(int i=0; i<n; ++i){
		//數字直接入棧 
		if(isdigit(A[i]))
			B[j++] = A[i];
		else if(A[i]=='(')
			sign.push(A[i]);
		else if(A[i]==')'){
			while(sign.top()!='('){
				B[j++] = sign.top();
				sign.pop();
			}
			sign.pop();//刪掉左括號 
		}
		//符號比較優先級 
		else{
			if(sign.empty())
				sign.push(A[i]);
			else{
				//A[i]與棧頂元素比較優先級,直到遇到'('或者棧空 
				while(!sign.empty() && sign.top()!='(' && you(A[i])<you(sign.top())){
					B[j++] = sign.top();
					sign.pop();
				}
				sign.push(A[i]);
			}
		} 
	} 
	//棧中如果還有符號,直接添加到B中就ok 
	while(!sign.empty()){
		B[j++] = sign.top();
		sign.pop();
	}
} 

int main(){
	char A[16] = "1+2*3+(4*5+6)*7";
	char B[16] = {0};
	in2post(A, B, 15);
	for(int i=0; i<15; ++i){
		cout << B[i] << ' ';
	}
	return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章