利用stack计算后缀表达式

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

struct stack{
	int capacity;
	int topofstack;
	double *a;
};

struct stack *createstack(int n){
	struct stack *s;
	s = (struct stack *)malloc(sizeof(struct stack));
	if(s == NULL){
		printf("Out of Space!\n");
		return NULL;
	}
	s->capacity = n;
	s->a = (double *)malloc(sizeof(double)*n);
	if(s->a == NULL){
		printf("Out of Space!\n");
		return NULL;
	}
	s->topofstack = -1;
	return s;
}

void push(double n,struct stack *s){
	if(s->topofstack<s->capacity-1)
		s->a[++s->topofstack] = n;
}

double popandtop(struct stack *s){
	if(s->topofstack>-1)
		return s->a[s->topofstack--];
}

int main(){
	struct stack *s;
	int i,flag,pointflag;
	double num,b,d,tmp1,tmp2;
	char ch[80],c;
	i = 0;
	s = createstack(10); //create stack
	while(scanf("%s",ch)){
		c = getchar();
		i = 0;
		num = 0;
		pointflag = 0;
		if(ch[i]>='0'&&ch[i]<='9'){  //if it's number push into stack
		while(ch[i]!='\0'){
			  	if(ch[i] == '.'){  //consider the decimal fraction stituation
			  		pointflag = 1;
			  		i++;
			  		continue;
			  	}
			  	if(pointflag){
			  		num += (ch[i] - '0')*pow(10,-pointflag);
			  		pointflag++;
			  	}
			  	else num = num*10 + ch[i] - '0';
			    i++;
		        }
		push(num,s);	
		}
		else
		switch(ch[i]){  //if it's operation pop two element , after operation push back the result
			case '+':push(popandtop(s) + popandtop(s),s);break;
			case '-':{       //sbustracion and division has order
				tmp1 = popandtop(s);
				tmp2 = popandtop(s);
				push(tmp2 - tmp1,s);
			}break;
			case '*':push(popandtop(s) * popandtop(s),s);break;
			case '/':{
				tmp1 = popandtop(s);
				tmp2 = popandtop(s);
				push(tmp2 / tmp1,s);
			}break;
			}
		if(c == '\n'||c == '\0')
		break;
	}
	printf("%lf",popandtop(s));
}                                                     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值