/*中缀式变后缀式
ACM队的"C小加"现在请你设计一个程序,帮助C小加把中缀表达式转换成后缀表达式。为简化问题,操作数均为个位数,操作符只有+-* / 和小括号。
【输入】
第一行输入T,表示有T组测试数据(T<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个表达式。这个表达式里只包含+-* /与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。并且输入数据不会出现不匹配现象。
【输出】
每组输出都单独成行,输出转换的后缀表达式。
【样例输入】
2
1+2
(1+2)*3+4*5
【样例输出】
12+
12+3*45*+
*/
/*字符栈内首先压入一个'#',作为判断栈是否为空的标志)
从字符串的左边开始遍历,若是数字就直接输出(其中输出有两种方式1、以字符输出,
2、以浮点型输出),成为后缀表达式的一部分;若是运算符,则与栈顶的运算符进行
比较,若 “当前>栈顶,则入栈,当前<=栈顶,则出栈“直至扫描结束,最后把#之前
的都输出。
*/
//中缀转后缀具体代码
#include <stdio.h>
#include <string.h>
#include <stack>
using namespace std;
stack <char> osta;
char s[1010];
int main()
{
int T;
osta.push('#');
scanf("%d",&T);
while(T--)
{
scanf("%s",s);
int len=strlen(s);
for(int i=0;i<len-1;i++)
{
if(s[i]=='(')
osta.push(s[i]);
else if(s[i]=='*'||s[i]=='/')
{
while(osta.top()=='*'||osta.top()=='/')
{
printf("%c ",osta.top());
osta.pop();
}
osta.push(s[i]);
}
else if(s[i]>='0'&&s[i]<='9')
{
while(s[i]>='0'&&s[i]<='9'||s[i]=='.')
{
printf("%c",s[i]);
i++;
}
i--;
printf(" ");
}
else if(s[i]=='+'||s[i]=='-')
{
while(osta.top()!='#'&&osta.top()!='(')
{
printf("%c ",osta.top());
osta.pop();
}
osta.push(s[i]);
}
else if(s[i]==')')
{
while(osta.top()!='(')
{
printf("%c ",osta.top());
osta.pop();
}
osta.pop();
}
}
while(osta.top()!='#')
{
printf("%c ",osta.top());
osta.pop();
}
printf("=\n");
}
return 0;
}
ACM队的"C小加"现在请你设计一个程序,帮助C小加把中缀表达式转换成后缀表达式。为简化问题,操作数均为个位数,操作符只有+-* / 和小括号。
【输入】
第一行输入T,表示有T组测试数据(T<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个表达式。这个表达式里只包含+-* /与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。并且输入数据不会出现不匹配现象。
【输出】
每组输出都单独成行,输出转换的后缀表达式。
【样例输入】
2
1+2
(1+2)*3+4*5
【样例输出】
12+
12+3*45*+
*/
/*字符栈内首先压入一个'#',作为判断栈是否为空的标志)
从字符串的左边开始遍历,若是数字就直接输出(其中输出有两种方式1、以字符输出,
2、以浮点型输出),成为后缀表达式的一部分;若是运算符,则与栈顶的运算符进行
比较,若 “当前>栈顶,则入栈,当前<=栈顶,则出栈“直至扫描结束,最后把#之前
的都输出。
*/
//中缀转后缀具体代码
#include <stdio.h>
#include <string.h>
#include <stack>
using namespace std;
stack <char> osta;
char s[1010];
int main()
{
int T;
osta.push('#');
scanf("%d",&T);
while(T--)
{
scanf("%s",s);
int len=strlen(s);
for(int i=0;i<len-1;i++)
{
if(s[i]=='(')
osta.push(s[i]);
else if(s[i]=='*'||s[i]=='/')
{
while(osta.top()=='*'||osta.top()=='/')
{
printf("%c ",osta.top());
osta.pop();
}
osta.push(s[i]);
}
else if(s[i]>='0'&&s[i]<='9')
{
while(s[i]>='0'&&s[i]<='9'||s[i]=='.')
{
printf("%c",s[i]);
i++;
}
i--;
printf(" ");
}
else if(s[i]=='+'||s[i]=='-')
{
while(osta.top()!='#'&&osta.top()!='(')
{
printf("%c ",osta.top());
osta.pop();
}
osta.push(s[i]);
}
else if(s[i]==')')
{
while(osta.top()!='(')
{
printf("%c ",osta.top());
osta.pop();
}
osta.pop();
}
}
while(osta.top()!='#')
{
printf("%c ",osta.top());
osta.pop();
}
printf("=\n");
}
return 0;
}