前缀转中缀(利用栈)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjck1995/article/details/50311351
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include<stack>
using namespace std;
struct node{
	int type;
	string s;
	void kuo(){
		s="("+s+")";
	}
	node(int t,string str){
		type=t;
		s=str;
	}
};
stack<node> sta;
char s[100];
void push(int t,string s){
	if(t==1){
		while(!sta.empty() && sta.top().type==1){
			node node1=sta.top();sta.pop();
			node node2=sta.top();sta.pop();
			s="("+node1.s+node2.s+s+")";
		}
		sta.push(node(1,s));
	}else{
		sta.push(node(0,s));
	}
}
int main()
{
    freopen("in","r",stdin);
    //freopen("out.txt","w",stdout);
   	while(gets(s)!=NULL){
		int len=strlen(s);
		while(!sta.empty()) sta.pop();
		for(int i=0;i<len;){
			if(s[i]>='0' && s[i]<='9' ){
				string tmp="";
				while(i<len && s[i]>='0' && s[i]<='9'){
					tmp+=s[i];
					i++;
				}
				push(1,tmp);
			}else if(s[i]>='a' && s[i]<='z' || s[i]>='A' && s[i]<='Z'){
				string tmp="";
				tmp+=s[i];
				push(1,tmp);
				i++;
			}else if(s[i]=='|' || s[i]=='&'
			         || s[i]=='>' && s[i+1]=='='
			        || s[i]=='<' && s[i+1]=='='
			        || s[i]=='=' && s[i+1]=='='
			        || s[i]=='!' && s[i+1]=='='
			        ){
				string tmp="";
				tmp+=s[i];
				tmp+=s[i+1];
				i+=2;
				push(0,tmp);
			}else{
				string tmp="";
				tmp+=s[i];
				push(0,tmp);
				i++;
			}
		}
		cout<<sta.top().s<<endl;

	}
    return 0;
}
input:
+-*+ABD/E+F*ADC

output:

((((A+B)*D)-(E/(F+(A*D))))+C)


阅读更多

没有更多推荐了,返回首页