2133数据结构实验之栈与队列三:后缀式求值and前缀式求值

数据结构实验之栈与队列三:后缀式求值
Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。

Input
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。

Output
求该后缀式所对应的算术表达式的值,并输出之。

Sample Input
59*684/-3*+#
Sample Output
57
Hint
基本操作数都是一位正整数!

Source

THINK:
是数字就入栈,注意不是一次性全部入栈,而是边入栈,边操作;
后缀式运算的时候是给top-1赋值,赋的值是top-1对top进行加减乘除的运算,之后top再减减,使其落再top-1上即可;从左往右进行扫描,操作的时候是栈次元素对栈顶元素进行操作
前缀式求值是:从右往左进行扫描,操作的时候是栈顶元素对栈次元素进行加减乘除的运算;最后输出栈顶元素;

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char s[200000];
int a[200000];
int main()
{
    scanf("%s",s);
    int len=strlen(s);
    int top=0;
    for(int i=0;i<len;i++)
    {
        if(s[i]>='0'&&s[i]<='9')
        {
            a[++top]=s[i]-'0';
        }
        else if(s[i]=='+')
        {
            a[top-1]=a[top-1]+a[top];
            top--;
        }
        else if(s[i]=='-')
        {
            a[top-1]=a[top-1]-a[top];
            top--;
        }
        else if(s[i]=='*')
        {
            a[top-1]=a[top-1]*a[top];
            top--;
        }
        else if(s[i]=='/')
        {
            a[top-1]=a[top-1]/a[top];
            top--;
        }
    }
    printf("%d\n",a[top]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/bhliuhan/article/details/81177761