数据结构-C语言版-栈(逆波兰)

 小甲鱼的逆波兰程序,我也看不懂,并且在VS上面有bug,以后学完一遍再回来看看

//实现对逆波兰输入的表达式的计算
//支持带小数点的数据
// a+(b-c)------>>>a b c - +
//a+(b-d)*d------>>-> a b c  - d  * +
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include <ctype.h>
#define Stack_Init_Size 20
#define StackInsert 10
#define MaxBuffer  10
typedef bool status;
typedef double ElemType;
typedef struct
{
	ElemType* base;
	ElemType* top;
	int StackSize;
}SqStack;
void  Initial(SqStack* s)
{
	if (!s->base)
	{
		exit(0);
	}
	s->base = (ElemType*)malloc(Stack_Init_Size * sizeof(ElemType));
	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 + StackInsert) * sizeof(ElemType));
		if (!s->base)
		{
			exit(0);
		}
		s->top = s->base + s->StackSize;
		s->StackSize = s->StackSize + StackInsert;
	}
	*(s->top) = e;
	s->top++;
}
void pop(SqStack* s, ElemType* e)
{
	if (!s->base)
	{
		exit(0);
	}
	s->top = s->top - 1;
	*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;
	//
	Initial(&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("\n出错,分母为0\n");
				return -1;
			}
			break;

		}
		scanf_s("%d,&c");
	}
	pop(&s, &d);
	printf("\n最终的计算机结果为 %f\n", d);
	//
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值