Uva-727 Equation(中缀表达式转后缀表达式)

题意:给你一些中缀表达式,求他们的后缀表达式。




分析:这题主要难点在空行的判断啊T_T.


<pre name="code" class="cpp">#include<iostream>
#include<cstdio>
#include<cstring>
#define N 1005
using namespace std;
const bool camp[7][7] =
{
	{1,1,0,0,0,1,1},{1,1,0,0,0,1,1},{1,1,1,1,0,1,1},
	{1,1,1,1,0,1,1},{0,0,0,0,0,0,0},{0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0}
};
char st[N];
struct Stackop
{
	int top;
	char date[N];
}s1;
int idx(char c)
{
	switch(c)
	{
		case '+' : return 0;
		case '-' : return 1;
		case '*' : return 2;
		case '/' : return 3;
		case '(' : return 4;
		case ')' : return 5;
		case '\0' : return 6;
	}
}
void gotval(int &pos)
{
	int now = 0;
	while(st[pos] >= '0' && st[pos] <= '9')
	{
		now = now*10 + st[pos] - '0';
		pos++;
	}
	pos--;
	printf("%d",now);                                        //输出其后缀表达式
}
void value()
{
	int pos = 0;
	while(st[pos] != '\0')
	{
		if(st[pos] >= '0' && st[pos] <= '9')
		{
			gotval(pos);
			while(s1.top && camp[idx(s1.date[s1.top])][idx(st[pos+1])]) printf("%c",s1.date[s1.top--]);
		}
		else
		{
			s1.date[++s1.top] = st[pos];
			if(s1.date[s1.top] == ')')
			{
				s1.top -= 2;
				while(s1.top && camp[idx(s1.date[s1.top])][idx(st[pos+1])]) printf("%c",s1.date[s1.top--]);
			}
		}
		pos++;
	}
    printf("\n");
}
int main()
{
    int T,temp;char c[2];
    scanf("%d",&T);
    getchar();
    getchar();
    while(T--)
    {
        temp = 0;
        while(gets(c) && c[0] != '\0') st[temp++] = c[0];
        st[temp] = '\0';
        value();
        if(T) printf("\n");
    }
}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值