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

Problem Description

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

Input

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

Output

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

Sample Input

59*684/-3*+#

Sample Output

57

Hint

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

Source

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

#define MAXSIZE 100
#define ERROR -9999999
typedef struct
{
    int num[MAXSIZE];
    int top;
}SeqStack;

void InitSeqStack(SeqStack* s)
{
    s->top = -1;
}

int IsEmpty(SeqStack *s)
{
    if (s->top == -1)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int Pop(SeqStack *s)
{
    if(!IsEmpty(s))
    {
        return s->num[s->top--];
    }
    return ;
}

void Push(SeqStack *s, int ch)
{
    if (s->top >= MAXSIZE-1)
    {
        return ERROR;
    }
    s->top++;
    s->num[s->top] = ch;
}

int GetTop(SeqStack *s)
{
    return s->num[s->top];
}



int main()
{
    SeqStack s;
    char str[100];
    scanf("%s", str);  // 正确的后缀表达式
    InitSeqStack(&s);
    int i = 0;
    while(str[i] != '#')
    {
        if (str[i] >= '0' && str[i] <= '9')  // 数字直接进栈
        {
            Push(&s, str[i]-'0');
        }
        else if (str[i] == '+')  // 若为操作符,则先弹出右操作数,再弹出左操作数
        {                        // 进行运算后,将结果压栈
            int a = Pop(&s);
            int b = Pop(&s);
            Push(&s, a+b);
        }
        else if (str[i] == '-')
        {
            int a = Pop(&s);
            int b = Pop(&s);
            Push(&s, b-a);
        }
        else if (str[i] == '*')
        {
            int a = Pop(&s);
            int b = Pop(&s);
            Push(&s, a*b);
        }
        else if (str[i] == '/')
        {
            int a = Pop(&s);
            int b = Pop(&s);
            Push(&s, b/a);
        }
        i++;
    }
    printf("%d", GetTop(&s));
    return 0;
}
原文地址:https://www.cnblogs.com/sugerandmaster/p/11530257.html