zoukankan      html  css  js  c++  java
  • 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,'',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
    ",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;
    }


     

  • 相关阅读:
    Lc169_多数元素
    Lc461_汉明距离
    有返回值的多线程
    Lc344_反转字符串
    Lc709_转换成小写字母
    Lc1436_旅行终点站
    Spring 注解回顾
    SpringCloud网关之Zuul
    SpringCloud注册中心之Zookeeper
    SpringCloud服务安全之hystrix
  • 原文地址:https://www.cnblogs.com/frankM/p/4399562.html
Copyright © 2011-2022 走看看