7-8 逆波兰表达式求值(20 分)

7-8 逆波兰表达式求值(20 分)提问

逆波兰表示法是一种将运算符(operator)写在操作数(operand)后面的描述程序(算式)的方法。举个例子,我们平常用中缀表示法描述的算式(1 + 2)*(5 + 4),改为逆波兰表示法之后则是1 2 + 5 4 + *。相较于中缀表示法,逆波兰表示法的优势在于不需要括号。
请输出以逆波兰表示法输入的算式的计算结果。

输入格式:

在一行中输入1个算式。相邻的符号(操作数或运算符)用1个空格隔开。

输出格式:

在一行中输出计算结果。

限制:

2≤算式中操作数的总数≤100
1≤算式中运算符的总数≤99
运算符仅包括“+”、“-”、“*”,操作数、计算过程中的值以及最终的计算结果均在int范围内。

输入样例1:

4 3 + 2 -

输出样例1:

5

输入样例2:

1 2 + 3 4 - *

输出样例2:


#include <stdlib.h>
#include <stdio.h>
#include <memory.h>//memset库源
#include<string.h> 
 

 
struct Stack
{
    int space[1000001];
    int top;
};
 
void init(struct Stack *s)
{
    s->top=0;
    memset(s->space,0,1000001);
}
 

 
int pop(struct Stack *s)
{
    return s->space[--s->top];
}
void push(struct Stack *s,char c)
{
    s->space[s->top++]=c;
}
 
int Is_empty(struct Stack *s)
{
    if(s->top==0)
        return 1;
    return 0;
}
int top(struct Stack*s)
{
	 return s->space[(s->top)-1];
}
int main()
{
	char c;
	struct Stack s;
	init(&s);
	while((c=getchar())!=EOF)
	{
		if(c=='\n')break;
		if(c!=' ')
		{
				if('0'<=c&&c<='9')
				{
					int num=(int)(c-'0');
					push(&s,num);
				}
				else
				{
						int x=pop(&s);
						int y=pop(&s);
						int rel;
					if(c=='+')
				      rel=x+y;
					else if(c=='-')
					  rel=y-x;
					else
				      rel=y*x;
				    push(&s,rel);
			}
		}
	
	}
	printf("%d",pop(&s));
	
	
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值