前缀转中缀(利用栈)

#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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值