表达式求值之求后缀式(亦即逆波兰式)

# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>

# define INIT_STACK_SIZE 10

typedef struct
{
	int * top;
	int * base;
	int stacksize;
}* PSTACK, STACK;

void init (PSTACK pS)
{
	pS->base = (int *)malloc(sizeof(int) * INIT_STACK_SIZE);

	if (!pS->base)
	{
		printf("内存分配失败!\n");

		exit(-1);
	}

	pS->top = pS->base;
	pS->stacksize = INIT_STACK_SIZE;

	return;
}

void pushNS (PSTACK pNS, char ch)
{
	*(pNS->top++) = ch;

	return;
}

void pushOS (PSTACK pOS, PSTACK pNS, char ch)
{
	bool change = false;
	char c = *(pOS->top - 1);

	if ((c == '+' || c == '-') && (ch == '*' || ch == '/'))
	{
		change = true;
	}

	if (change || ch == '(' || c == '(' || pOS->top == pOS->base)
	{
		*(pOS->top++) = ch;
	}
	else if (ch == ')')
	{
		while (*(pOS->top - 1) != '(')
		{
			pushNS(pNS, *(--pOS->top));
		}

		--pOS->top;
	}
	else
	{
		pushNS(pNS, *(--pOS->top));
		*(pOS->top++) = ch;

		if ((*(pOS->top - 2) == '-' || *(pOS->top - 2) == '+') && (*(pOS->top - 1) == '+' || *(pOS->top - 1) == '-'))
			//对-*+之类的情况变成-+的处理
		{
			pushNS(pNS, *(pOS->top - 2));
			*(pOS->top - 2) = *(pOS->top - 1);
			--pOS->top;
		}
	}

	return;
}

void getsuffix (PSTACK pOS, PSTACK pNS, char ch)
{
	if ('\n' == ch)
	{
		while (pOS->top != pOS->base)
		{
			pushNS(pNS, *(--pOS->top));
		}

		return;
	}

	if ('+' == ch || '-' == ch || '*' == ch || '/' == ch || '(' == ch || ')' == ch)
	{
		pushOS(pOS, pNS, ch);
	}
	else
	{
		pushNS(pNS, ch);
	}

	return;
}

void traverse (PSTACK pS)
{
	for (int i = 0; i < (pS->top - pS->base); ++i)
	{
		printf("%c", *(pS->base + i));
	}

	return;
}

int main(void)
{
	char ch;

	STACK os;
	STACK ns;

	init(&os);
	init(&ns);

	printf("请输入表达式(回车代表输入完成):");

	do
	{
		ch = getchar();

		getsuffix(&os, &ns, ch);
	}while ('\n' != ch);

	printf("\n后缀式:");

	traverse(&ns);

	printf("\n");

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值