暑假集训day6——数据结构实验之栈与队列三:后缀式求值

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic Discuss

Problem Description

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

Input

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

Output

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

Sample Input

59*684/-3*+#

Sample Output

57

Hint

基本操作数都是一位正整数!

Source

/*注意:基本操作数都是一位正整数!基本操作数都是一位正整数!基本操作数都是一位正整数!!!(重要的事情说三遍!!)*/

#include<stdio.h>
#include<string.h>

char str[1000001];

int main(void)
{
    int top, i, len, a[10001];

    scanf("%s", str);
    len = strlen(str);
    top = -1;

    memset(a, 0, sizeof(a));

    for(i = 0; i < len; i++)
    {
        if(str[i] >= '0' && str[i] <= '9')
        {
            a[++top] = str[i] - '0';
        }

        else
        {
            if(str[i] == '*')
            {
                a[top - 1] *= a[top];
                top--;
            }

            else if(str[i] == '/')
            {
                a[top - 1] /= a[top];
                top--;
            }

            else if(str[i] == '+')
            {
                a[top - 1] += a[top];
                top--;
            }

            else
            {
                a[top - 1] -= a[top];
                top--;
            }
        }
    }

    //printf("%d\n", top);   (数组a最终里面就剩下最终的值了呀~~,因为其他的都被用掉来求值了呀呀~~~~所以最终top==-1)

    printf("%d\n", a[0]);

    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/Eider1998/article/details/81411376