NYOJ 257 郁闷的C小加(一)

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=257

 

后缀表达式:依次读入字符,

1>当为数字时,直接进入表达式;

2>为左括号时,入栈;

2>为右括号时,弹栈进入表达式,直到遇见第一个右括号。并将读入的右括号和栈中的左括号丢弃;

3>为除括号外的其他运算符时,判断优先级:

          若当前读入的运算符优先级小于或等于栈顶的运算符时,弹栈进入表达式,直到栈顶的运算符优先级小于当前读入的运算符。再将当前读入的运算符入栈(如果栈为空,则直接入栈)

4>将栈中剩余的字符弹出到表达式.

 

 

#include <stdio.h>
#include <string.h>
char stack[1005];
char suffix[1005];
char buffer[1005];
int s_top=0;

int main()
{
	void s_push(char x);
	char s_pop(void);
	bool priority(char top_op,char InfixExp_op);
	bool isoperator(char c);
	int t;
	int i;
	int j;
	scanf("%d",&t);
	while(t--)
	{
		memset(suffix,'\0',sizeof(suffix));
		s_top=0;
		scanf("%s",buffer);
		for (i=0,j=0;i<strlen(buffer);i++)
		{
			if(buffer[i]>='0'&&buffer[i]<='9')				//为数字,直接进入后缀表达式
				suffix[j++]=buffer[i];

			if(buffer[i]=='(')							//左括号,入栈
				s_push('(');

			if(buffer[i]==')')							//右括号,弹栈到左括号
			{
				while(stack[s_top]!='(')  
					suffix[j++]=s_pop();
				s_pop();									//丢弃'('

			}

			if(isoperator(buffer[i]) ) 
			{
				if(s_top==0)
					s_push(buffer[i]);
				else
				{

					while( priority(stack[s_top],buffer[i]) &&s_top!=0  )		//运算符,判断优先级
						suffix[j++]=s_pop();

					s_push(buffer[i]);
				}

			}

		}
		while(s_top)
			suffix[j++]=s_pop();
		printf("%s\n",suffix);

	}


}

void s_push(char x)
{
	s_top++;
	stack[s_top]=x;

}

char s_pop(void)
{
	if(s_top)
	{

		return stack[s_top--];
	}

}

bool priority(char top_op,char InfixExp_op)
{

	if(top_op=='(')
		return false;

	if(top_op=='*'||top_op=='/')		//当前处理的运算符小于或等于栈顶的运算符时
		return true;

	if(InfixExp_op=='+'||InfixExp_op=='-')
		return true;

	return false;


}
bool isoperator(char c)			//判断是不是运算符
{
	if(c=='+'||c=='-'||c=='*'||c=='/')
		return true;
	return false;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值