栈的应用实例——计算后缀表达式

红心用户输入一个后缀表达式,程序计算该后缀表达式的值并输出结果:

/* postfix_expression.c */

#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    int i, flag;
    char c, data_string[10];
    float data, f1, f2, result;
    stack data_stack;
    
    data_stack = create_stack(100);
    printf("Please input a postfix expression:
");

    i = 0;
    for(c = getchar(); c != '
'; c = getchar())
    {
        switch(c)
        {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':    
            case '9':
            case '.':
                flag = 1;
                data_string[i++] = c;
                break;
            case ' ':
                if(flag == 1)
                {
                    data_string[i] = '';
                    data = atof(data_string);
                    push(data, data_stack);
                
                    i = 0;
                    data_string[0] = '';
                }
                break;
            case '+':
                flag = 0;
                f1 = top_and_pop(data_stack);
                f2 = top_and_pop(data_stack);
                result = f1 + f2;
                push(result, data_stack);
                break;
            case '-':
                flag = 0;
                f1 = top_and_pop(data_stack);
                f2 = top_and_pop(data_stack);
                result = f1 - f2;
                push(result, data_stack);
                break;
            case '*':
                flag = 0;
                f1 = top_and_pop(data_stack);
                f2 = top_and_pop(data_stack);
                result = f1 * f2;
                push(result, data_stack);
                break;
            case '/':
                flag = 0;
                f1 = top_and_pop(data_stack);
                f2 = top_and_pop(data_stack);
                result = f1 / f2;
                push(result, data_stack);
                break;
        }
    }
    result = top_and_pop(data_stack);
    printf("result = %.2f
", result);
}

上面的程序中所使用的stack.h参考http://www.cnblogs.com/nufangrensheng/p/3610520.html。(注:stack.h中使用的是

typedef int element_type;

红心测试实例:

后缀表达式 6 5 2 3 + 8 * + 3 + * 的中缀表达式(我们平常使用的形式)为:6 * { [ 5 + ( 2 + 3 ) * 8 ] + 3 } = 288.

测试结果:

image

原文地址:https://www.cnblogs.com/nufangrensheng/p/3615059.html