Program work 4. Infix expression convert to Prefix expression (Ⅱ)

来源:互联网 发布:mac版office激活 编辑:程序博客网 时间:2024/05/18 18:00

目的:    计算前缀表达式的结果

思路:    由于前缀操作数已经是"带括号"的运算, 所以可以直接运算. 本program只考虑简单的四则运算, 不考虑负数.

1. 用一个堆栈存放中间结果.

2. 从右往左扫描前缀表达式.

a. 如果遇到操作数, 直接压进栈

b. 遇到运算符, 将栈顶元素弹出置于左操作数, 再弹出一个栈顶元素置于右操作数. 然后进行运算: 左操作数 运算符 右操作数. 生成结果压入栈中

3. 扫描后, 将栈中的结果输出便是答案


Program environment:

               OS:  Ubuntu 14.04 32 bits

               IDE:   Eclipse

       Language:     C++

       Compiler:       g++

Input & Output:

A legal prefix expression string is considered to be an input of the program, but only available for arithmetic (+, -, *, /) and ignore the negative integer. Enter -1 to terminate the program.

Program will print out the evaluation of the input as the result.

Ex: input:-+1*58*3+25

output:20

Program description:

1.     Create an empty stack called re for keeping temp result.

2.     Scan the input prefix expression from right to left.

a.     If the character is an operand,convert it to integer type then push it into the re stack.

b.     If the character is an operator, get two top-most elements from re. Then calculate the operation, the result --- a new integer would be pushed into the re stack.

3.     After the scan, there’s only one integer in the re stack, that’s the result and print it out.


//============================================================================// Name        : Sicily.cpp// Author      : Reid Chan// Version     :// Copyright   : Your copyright notice//============================================================================#include <iostream>#include <string>#include <cctype>#include <stack>using namespace std;int tmp_result(int l, int r, char op){int re;if (op == '+') {re = l + r;} else if (op == '-') {re = l - r;} else if (op == '*') {re = l * r;} else {re = l / r;}return re;}int main(){string prefix;stack<int> re;while (cin >> prefix && prefix != "-1") {int len = prefix.length();char ch;for (int i = len - 1; i >= 0; --i) {ch = prefix[i];if (isdigit(ch)) {re.push((ch - '0')); // if it is operand, convert it to int type and push into stack} else {int left = re.top(); // if it is operator, get the two top-most from stackre.pop();  // to calculate the operation.int right = re.top();re.pop();re.push(tmp_result(left, right, ch));}}cout << re.top() << endl; // print out the result.re.pop();}return 0;}


0 0
原创粉丝点击