栈 表达式求值算法c/c++

表达式求值,一般采用栈和队列的方式来求值,下面介绍表达式求值的两种算法。

方法一、使用两个栈,一个为操作符栈OPTR(operator),一个是操作数栈OPND(operand)
算法过程:
当输入 3 * ( 4 - 1 * 2 ) + 6 / ( 1 + 1 )时,先将输入的数据存储在一个字符数组中,按照字符的顺序一个一个的处理,比如

ch = getchar()
  • 1
  • 2

然后根据ch 的值判断。

  • ch 是数字,直接压入操作数栈OPND
  • ch'(',直接入栈OPTR;若 ch')',若OPTROPND 非空,弹出OPTR的栈顶操作符,弹出OPND栈顶的两个操作数,做运算,然后见个结果压入栈OPND,直到弹出的OPTR栈顶元素时')';
  • ch 是操作符(比如+, -, *, /),如果OPTR栈顶元素是 (,直接入栈OPTR,如果不是'('OPTR栈非空且栈顶元素操作符的优先级大于ch,那么弹出OPTR的栈顶操作符,并弹出OPND中栈顶的两个元素,做运算,将运算结果入栈OPND,此时,重复这一步操作;否则将ch入栈OPTR
  • ch为EOF,说明表达式已经输入完成,判断OPTR是否为空,若非空,一次弹出OPTR栈顶操作符,并与OPND栈顶两个元素做运算,将运算结果入栈OPND,最后表达式的结果即OPND的栈底元素。

以表达式3 * ( 4 - 1 * 2 ) + 6 / ( 1 + 1 )为例,计算过程如下所示:

OPTROPNDch备注
 33 
*3* 
*,(3( 
*,(3,44 
*,(,-3,4- 
*,(,-3,4,11 
*,(,-,*3,4,1* 
*,(,-,*3,4,1,22 
*,(,-3,4,2)OPND弹出2和1,OPTR弹出*,计算结果入栈OPND
*,(3,2)OPND弹出2和4,OPTR弹出-,计算结果入栈OPND
*3,2)OPTR栈顶弹出的是)
+6+OPTR栈顶元素优先级大于ch,将OPND栈的3和2与OPTR的*运算,结果入栈OPND,ch入栈OPTR
+6,66 
+,/6,6/ 
+,/,(6,6( 
+,/,(6,6,11 
+,/,(,+6,6,1+ 
+,/,(,+6,6,1,11 
+,/,(6,6,2)OPND的1和1,与OPTR的+运算,结果入栈OPND
+,/6,6,2) 
+6,3 表达式已经输入完成,OPTR非空,继续计算。OPND的2和6,OPTR的/运算
 9 计算结果
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stack>
#include <cmath>

using namespace std;

char s[1000];
int  g_pos;  // 字符数组的下标

/* 字符转数字 */
double Translation(int & pos)
{
    double integer = 0.0;    // 整数部分
    double remainder = 0.0;  // 余数部分

    while (s[pos] >= '0' && s[pos] <= '9')
    {
        integer *= 10;
        integer += (s[pos] - '0');
        pos++;
    }

    if (s[pos] == '.')
    {
        pos++;
        int c = 1;
        while (s[pos] >= '0' && s[pos] <= '9')
        {
            double t = s[pos] - '0';
            t *= pow(0.1, c);
            c++;
            remainder += t;
            pos++;
        }
    }

    return integer + remainder;
}

/* 返回运算符级别 */
int GetLevel(char ch)
{
    switch (ch)
    {
    case '+':
    case '-':
        return 1;
    case '*':
    case '/':
        return 2;
    case '(':
        return 0;
    case '#':
        return -1;
    };
}

/* 对两个数进行运算 */
double Operate(double a1, char op, double a2)
{
    switch (op)
    {
    case '+':
        return a1 + a2;
    case '-':
        return a1 - a2;
    case '*':
        return a1 * a2;
    case '/':
        return a1 / a2;
    };
}

/* 利用两个栈进行模拟计算 */
double Compute()
{
    stack<char> optr;    // 操作符栈
    stack<double> opnd;  // 操作数栈

    optr.push('#');      //置于符栈顶
    int len = strlen(s);
    bool is_minus = true;  // 判断'-'是减号还是负号, true表示负号

    for (g_pos = 0; g_pos < len;)
    {
        //1. 负号
        if (s[g_pos] == '-' && is_minus)  // 是负号
        {
            opnd.push(0);
            optr.push('-');
            g_pos++;
        }
        //2. 是右括号 )
        else if (s[g_pos] == ')')
        {
            is_minus = false;
            g_pos++;

            while (optr.top() != '(')
            {
                double a2 = opnd.top();
                opnd.pop();
                double a1 = opnd.top();
                opnd.pop();
                char op = optr.top();
                optr.pop();

                double result = Operate(a1, op, a2);
                opnd.push(result);
            }
            optr.pop();  // 删除'('
        }
        //3. 数字
        else if (s[g_pos] >= '0' && s[g_pos] <= '9')
        {
            is_minus = false;
            opnd.push(Translation(g_pos));
        }
        //4. ( 左括号
        else if (s[g_pos] == '(')
        {
            is_minus = true;
            optr.push(s[g_pos]);
            g_pos++;
        }
        //5. + - * / 四种
        else
        {
            while (GetLevel(s[g_pos]) <= GetLevel(optr.top()))    //当前优先级小于栈尾优先级
            {
                double a2 = opnd.top();
                opnd.pop();
                double a1 = opnd.top();
                opnd.pop();
                char op = optr.top();
                optr.pop();

                double result = Operate(a1, op, a2);
                opnd.push(result);
            }

            optr.push(s[g_pos]);
            g_pos++;
        }
    }

    while (optr.top() != '#')
    {
        double a2 = opnd.top();
        opnd.pop();
        double a1 = opnd.top();
        opnd.pop();
        char op = optr.top();
        optr.pop();

        double result = Operate(a1, op, a2);
        opnd.push(result);
    }

    return opnd.top();
}

int main()
{
    while (cin >> s)
        cout << "结果为:" << Compute() << endl << endl;

    return 0;
}



  • 18
    点赞
  • 91
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
下面是一种用C语言实现中缀表达式求值算法: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAX_SIZE 100 typedef struct Stack { int top; int data[MAX_SIZE]; } Stack; int is_empty(Stack *s) { return s->top == -1; } int is_full(Stack *s) { return s->top == MAX_SIZE - 1; } void push(Stack *s, int value) { if (is_full(s)) { printf("Stack is full.\n"); exit(1); } s->top++; s->data[s->top] = value; } int pop(Stack *s) { if (is_empty(s)) { printf("Stack is empty.\n"); exit(1); } int value = s->data[s->top]; s->top--; return value; } int peek(Stack *s) { if (is_empty(s)) { printf("Stack is empty.\n"); exit(1); } return s->data[s->top]; } int priority(char op) { switch (op) { case '+': case '-': return 1; case '*': case '/': return 2; default: return 0; } } int evaluate(int op1, int op2, char op) { switch (op) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1 * op2; case '/': return op1 / op2; default: return 0; } } int infix_to_postfix(char *infix, char *postfix) { int i, j; Stack s; s.top = -1; for (i = 0, j = 0; infix[i] != '\0'; i++) { if (isdigit(infix[i])) { postfix[j++] = infix[i]; } else if (infix[i] == '(') { push(&s, infix[i]); } else if (infix[i] == ')') { while (!is_empty(&s) && peek(&s) != '(') { postfix[j++] = pop(&s); } if (is_empty(&s)) { printf("Invalid expression.\n"); exit(1); } pop(&s); } else if (infix[i] == '+' || infix[i] == '-' || infix[i] == '*' || infix[i] == '/') { while (!is_empty(&s) && peek(&s) != '(' && priority(infix[i]) <= priority(peek(&s))) { postfix[j++] = pop(&s); } push(&s, infix[i]); } else { printf("Invalid character: %c\n", infix[i]); exit(1); } } while (!is_empty(&s)) { if (peek(&s) == '(') { printf("Invalid expression.\n"); exit(1); } postfix[j++] = pop(&s); } postfix[j] = '\0'; return j; } int evaluate_postfix(char *postfix) { int i; Stack s; s.top = -1; for (i = 0; postfix[i] != '\0'; i++) { if (isdigit(postfix[i])) { push(&s, postfix[i] - '0'); } else if (postfix[i] == '+' || postfix[i] == '-' || postfix[i] == '*' || postfix[i] == '/') { int op2 = pop(&s); int op1 = pop(&s); int result = evaluate(op1, op2, postfix[i]); push(&s, result); } else { printf("Invalid character: %c\n", postfix[i]); exit(1); } } if (s.top != 0) { printf("Invalid expression.\n"); exit(1); } return pop(&s); } int main() { char infix[MAX_SIZE], postfix[MAX_SIZE]; printf("Enter an infix expression: "); fgets(infix, MAX_SIZE, stdin); infix[strcspn(infix, "\n")] = '\0'; int length = infix_to_postfix(infix, postfix); printf("Postfix expression: %s\n", postfix); int result = evaluate_postfix(postfix); printf("Result: %d\n", result); return 0; } ``` 该算法使用两个,一个用于转换中缀表达式为后缀表达式,另一个用于求解后缀表达式。其中,转换中缀表达式为后缀表达式的过程中,遇到操作数直接输出到后缀表达式中,遇到左括号直接压入中,遇到右括号则将中元素弹出直到遇到左括号,并将左右括号都丢弃。遇到操作符时,如果顶元素为左括号,则直接将操作符压入中;否则,将中优先级大于等于当前操作符的元素都弹出,直到为空或顶元素为左括号,并将当前操作符压入中。转换完成后,如果中还有元素,则依次弹出并输出到后缀表达式中。 求解后缀表达式的过程中,遇到操作数则直接压入中,遇到操作符则弹出顶的两个元素作为操作数,计算结果并将结果压入中。最终,如果中只有一个元素,则该元素即为表达式的值。如果中元素多于一个,则表明表达式有误。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值