• 数据结构实验之栈二:一般算术表达式转换成后缀式


    数据结构实验之栈二:一般算术表达式转换成后缀式

    Time Limit: 1000MS Memory Limit: 65536KB

    Problem Description

    对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。

    Input

    输入一个算术表达式,以‘#’字符作为结束标志。

    Output

    输出该表达式转换所得到的后缀式。

    Example Input

    a*b+(c-d/e)*f#

    Example Output

    ab*cde/-f*+

    #include <stdio.h>
    #include <stdlib.h>
    #include <malloc.h>
    #define stack_size 1000
    #define stackincreament 100
    typedef int element;
    typedef struct
    {
    	element *base;//栈低元素
    	element *top;//栈顶元素
    	int stacksize;
    }Stack;
    int initializer_list(Stack &S) //初始化栈
    {
        S.base = (element *)malloc(sizeof(element)*stack_size);
        if(!S.base) exit(-1);
        S.top = S.base;
        S.stacksize = stack_size;
        return 1;
    }
    int push(Stack &S,char &e) //进栈
    {
    	if(S.top - S.base >=S.stacksize)
    	{
    		S.base = (element *)realloc(S.base,(sizeof(element)*(S.stacksize+stackincreament)));
    		if(S.base) exit(-1);
    		S.top = S.base + S.stacksize;
    		S.stacksize +=stackincreament;
    	}
    
    	*S.top++ = e;
    	return 0;
    }
    int pop(Stack &S)//出栈
    {
    	if(S.base==S.top)
    	{
    		return -1;
    	}
    	S.top--;
    	printf("%c",*S.top);
    	return 0;
    }
    void change(Stack &S,char str[])
    {
    	int i=0;
    	while(str[i]!='#')
    	{
    		if(str[i]>='a' && str[i]<='z')
    		{
    			printf("%c",str[i]);
    		}
    		else if(str[i]=='*' || str[i]=='/')
    		{
    			push(S,str[i]);
    		}
    		else if(str[i]=='+'||str[i]=='-')
    		{
    			if(*(S.top-1)=='*' || *(S.top-1)=='/')
    			{
    				pop(S);
    			}
    			push(S,str[i]);
    		}
    		else if(str[i]=='(')
    		{
    			push(S,str[i]);
    		}
    		else if(str[i]==')')
    		{
    			while(*(S.top-1)!='(')
    			{
    				pop(S);
    			}
    			S.top--;
    		}
    		i++;
    	}
    	while(S.base!=S.top)
    	{
    		pop(S);
    	}
    	printf("\n");
    }
    int main()
    {
        Stack S;
        initializer_list(S);
    	char string[123];
    	scanf("%s",string);
    	change(S,string);
    	
    	return 0;
    }
    
    

  • 相关阅读:
    VS2010引用App_Code下的类文件问题解决方法
    Sql server 2008 sa用户开启教程
    ASP.NET中App_Code,App_Data等文件夹的作用
    错误提示: (provider: Named Pipes Provider, error: 40 Could not open a connection to SQL Server)
    treeview展开一个节点就关闭其他节点
    ASP.NET AJAX Toolkit的安装过程
    c++推荐读物
    for()的多参数
    模板函数I n p u t
    这次真的是下定决心了
  • 原文地址:https://www.cnblogs.com/CCCrunner/p/11782138.html
Copyright © 2020-2023  润新知