逆波兰表达式计算

举个例子:
(1-2)*(4+5)

将上述表达式改写为逆波兰表达式
1 2 - 4 5 + *
然后用栈实现逆波兰表达式的计算:一下代码用C语言实现

可以用栈来实现逆波兰表达式的计算;
数字1 2进栈,遇到运算符 - 弹出__1 2__相减,得到-1,将-1入栈
数字4 5 进栈,遇到运算符__+__ 弹出__4 5__相加,得到9, 将9入栈
遇到__*__,- 1 * 9 得到计算结果-9.
栈空无数据压栈 输出计算结果

#include
#include
#include

#define STACK_INIT_SIZE  20
#define STACKINCREAMENT 10
#define MAXBUFFER        10

typedef double ElemType;
typedef struct {
	ElemType* base;
	ElemType* top;
	int stacksize;
}sqStack;

void InitStack(sqStack* s) 
{
	s->base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
	if (!s->base)
		exit(0);

	s->top = s->base;
	s->stacksize = STACK_INIT_SIZE;
}
void Push(sqStack* s,ElemType e)
{
	if (s->top - s->base >= s->stacksize)
	{
		s->base = (ElemType*)realloc(s->base, (s->stacksize + STACKINCREAMENT) * sizeof(ElemType));
		if (!s->base)
			exit(0);
		s->top = s->base + s->stacksize;
		s->stacksize = s->stacksize + STACKINCREAMENT;
	}
	*(s->top) = e;
	s->top++;
}
void Pop(sqStack* s,ElemType *e)
{
	if (s->top == s->base)
		return;
	*e = *--(s->top);
}
int StackLen(sqStack s)
{
	return (s.top - s.base);
}
int main(){
	sqStack s;
	char c;
	double d, e;
	char str[MAXBUFFER];
	int i = 0;
	InitStack(&s);
	printf("请按逆波兰表达式输入待计算数据 数据与运算符用空格 隔开,以#作为结束标志\n");
	scanf_s("%c",&c);


	while (c != '#')
	{
		while (isdigit(c)|| c=='.') //用于过滤数字
		{
			str[i++] = c;
			str[i] = '\0';
			if (i >= 10)
			{
				printf("输入单个数据过大\n");
				return-1;
			}
			scanf_s("%c", &c);
			if (c == ' ')
			{
				d = atof(str);
				Push(&s, d);
				i = 0;
				break;
			}
		}
		switch (c)
		{
		case '+':
			Pop(&s,&e); 
			Pop(&s,&d);
			Push(&s,d+e);
			break;
		case '-':
			Pop(&s,&e);
			Pop(&s,&d);
			Push(&s,d-e);
			break;
		case '*':
			Pop(&s,&e);
			Pop(&s,&d);
			Push(&s,d*e);
			break;
		case '/':
			Pop(&s,&e);
			Pop(&s,&d);
			if (e != 0)
			{
				Push(&s,d/e);
			}
			else
			{
				printf("error 除数为0 \n");
				return -1;
			}
			break;
		default:
			break;
		}
		scanf_s("%c",&c);
	}
	Pop(&s,&d);
	printf("最终的计算结果为:%f\n",d);
	return 0;
}

你可能感兴趣的:(数据结构和算法)