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

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

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;
}


posted @ 2016-09-28 21:32  Philtell  阅读(103)  评论(0编辑  收藏  举报