栈之逆波兰式计算

逆波兰式(Reverse Polish notation,RPN,或逆波兰记法),也叫后缀表达式(将运算符写在操作数之后)

如:我们平时写a+b,这是中缀表达式,写成后缀表达式就是:ab+

(a+b)*c-(a+b)/e的后缀表达式为:ab+c*ab+e/-

#include
#include "stdlib.h"
#include
#include "ctype.h"
using namespace std;
#define STACK_SIZE 100
#define STACKINCREMENT 10
#define MAXBUFFER 10//输入单个数长度最大值
typedef double ElemType;

struct sqStack
{
	ElemType *top;
	ElemType *base;
	int  stackSize;
};
void InitStack(sqStack *s)
{
	s->base=(ElemType*)malloc(sizeof(ElemType)*STACK_SIZE);
	if(!s->base)
		exit(0);
	s->top=s->base;
	s->stackSize=STACK_SIZE;

}

void Push(sqStack *s,ElemType e)
{
	if(s->top-s->base>=s->stackSize)
	{
		s->base=(ElemType*)realloc(s->base,(s->stackSize+STACKINCREMENT)*sizeof(ElemType));
		if(!s->base)
		    exit(0);
		s->top=s->base+s->stackSize;
		s->stackSize=s->stackSize+STACKINCREMENT;
	}
	*(s->top)=e;
	s->top++;
	
}
void Pop(sqStack *s,ElemType *e)
{
	if(s->top==s->base)
		return;
	s->top--;
	*e=*(s->top);


}
//清空一个栈,不改变物理内存(即可恢复)
void Clear(sqStack *s)
{
	s->top=s->base;
}

//销毁一个栈(改变内存)
void Destroy(sqStack *s)
{
	for(int i=0;istackSize;i++)
	{
		free(s->base);
		s->base++;
	}
	s->base=s->top=NULL;
	s->stackSize=0;

}

//计算栈的当前容量
int Stacklen(sqStack *s)
{
	return (s->top-s->base);
}

//利用栈的结构特点。将二进制转化为十进制

int main()
{
	sqStack s;
	char c;
	double d,e;
	InitStack(&s);
	char str[MAXBUFFER];
	int i=0;
	printf("请按照逆波兰表达式输入待计算数据");
	scanf("%c",&c);
	while(c!='#')
	{
		while(isdigit(c)||c=='.')//将输入的字符转换为double型数据
		{
			str[i++]=c;
			str[i]='\0';
			if(i>=10)
			{
				printf("出错:输入单个数字太大\n");
				return -1;
			}
			scanf("%c",&c);
			if(c==' ')//空格表示单个数据结束
			{
				d=atof(str);
				Push(&s,d);
				i=0;
				break;
			}
			
		}
		switch(c)
		{
			case '+':
				Pop(&s,&d);
				Pop(&s,&e);
				Push(&s,d+e);
				break;
			case '-':
				Pop(&s,&d);
				Pop(&s,&e);
				Push(&s,e-d);
				break;
			case '*':
				Pop(&s,&d);
				Pop(&s,&e);
				Push(&s,e*d);
				break;
			case '/':
				Pop(&s,&d);
				Pop(&s,&e);
				if(d!=0)
				{
					Push(&s,e/d);
				}
				else
				{
					printf("除数不可以为0!");
					return -1;
				}
				break;
		}
		scanf("%c",&c);
	}
	Pop(&s,&d);
	printf("运算结果是:%f\n",d);
	return 0;

}



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