后缀表达式求值
2013-02-27 19:21
281 查看
一、问题描述
将用户输入的前缀表达式转化为后缀表达式后,就可以计算表达式的值。本文给出后缀表达式求值的具体实现。
例:有前缀表达式:8-(3+2*6)/5+4;转化为后缀表达式后为:8 3 2 6 * + 5 / - 4 +
二、算法实现
1.后缀表达式存储在一维数组中,遍历数组;
2.遍历过程中,当遇到的是数字时,则直接将其push到栈中;
3.当遇到的是标点符号时,则依次从栈中弹出两个数字,计算组成的表达式的值,并将结果入栈;
4.遍历结束后,栈中会有一个值,就是最终结果,将其弹出即可。
三、代码
将用户输入的前缀表达式转化为后缀表达式后,就可以计算表达式的值。本文给出后缀表达式求值的具体实现。
例:有前缀表达式:8-(3+2*6)/5+4;转化为后缀表达式后为:8 3 2 6 * + 5 / - 4 +
二、算法实现
1.后缀表达式存储在一维数组中,遍历数组;
2.遍历过程中,当遇到的是数字时,则直接将其push到栈中;
3.当遇到的是标点符号时,则依次从栈中弹出两个数字,计算组成的表达式的值,并将结果入栈;
4.遍历结束后,栈中会有一个值,就是最终结果,将其弹出即可。
三、代码
#include <stdio.h> #include <stdlib.h> #include "stack_yutao.h" void display_array(int array[]); int postfix_caculation(int postfix_array[]); elemtype caculate_value(elemtype a, elemtype array_i,elemtype b); void convert_to_int(char postfix_array[], int postfix_int[]); int main() { int ans = 0; char postfix_array[] = "8326*+5/-4+"; int postfix_int[15];//how to define the size ??? convert_to_int(postfix_array,postfix_int); // display_array(postfix_int); ans = postfix_caculation(postfix_int); printf("This postfix array's value is %d !\n",ans); system("pause"); return 0; } //计算后缀表达式的值 int postfix_caculation(int postfix_int[]) { elemtype result = 0; int i = 0; elemtype num1, num2, temp; int stack_size = 10; //定义栈的大小为10 stack char_stack; //声明栈 stack *s = &char_stack; initStack(s,stack_size); //初始化栈 while(postfix_int[i] != '\0') //遍历后缀表达式 { if(0 <= postfix_int[i] && postfix_int[i] <= 9) { push(s,postfix_int[i]); }else { get_top(s,&num1); pop(s); get_top(s,&num2); pop(s); temp = caculate_value(num2,postfix_int[i],num1); push(s,temp); } i ++; } get_top(s,&result); return result; } elemtype caculate_value(elemtype a, char array_i,elemtype b) { elemtype result; switch(array_i) { case '+': result = a + b; break; case '-': result = a - b; break; case '*': result = a * b; break; case '/': result = a / b; break; default: printf("wrong postfix_array !\n"); break; } return result; } void convert_to_int(char postfix_array[], int postfix_int[]) { int i = 0; while(postfix_array[i] != '\0') { if('0' <= postfix_array[i] && postfix_array[i] <= '9') { postfix_int[i] = postfix_array[i] - '0'; }else { postfix_int[i] = postfix_array[i]; } i ++; } postfix_int[i] = '\0'; } //输出数组中的内容 void display_array(int array[]) { int i = 0; while(array[i] != '\0') { printf("%d ",array[i++]); } printf("\n"); }
相关文章推荐
- 表达式求值(前缀、中缀、后缀)
- 前缀、中缀、后缀表达式及其求值
- 中缀表达式转后缀表达式并求值
- 中缀表达式转换成后缀表达式以及逆波兰表示法求值
- 中缀表达式转成后缀表达式 后缀表达式求值
- 算术表达式系列之后缀表达式求值
- C语言 实现中缀表达式转后缀表达式并求值
- 表达式求值(中缀变后缀再求值)
- 后缀表达式实现表达式求值
- 后缀表达式求值
- 后缀表达式加表达式求值
- C++Primer 练习9.52(续) 中缀表达式转后缀表达式求值
- 编程对一个逆波兰式(后缀表达式)进行求值,如“435*+23*-”的结果是13,函数的参数为字符串(后缀表达式),假定字符串为正确的逆波兰式。
- 中后缀表达式的相互转换和四则运算表达式求值
- NYOJ1272 表达式求值(后缀求值,特殊处理)(河南省第九届ACM省赛)
- 数据结构上机题目4--后缀表达式求值
- 栈的应用-后缀表达式运算求值
- 后缀表达式求值
- 后缀表达式的求值的算法
- 后缀表达式的求值的算法