Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Expression Evaluation Using Stack

Tech May 16 1

Problem Description

This solution processes mathematical expressions containing single-digit operands (0-9), operators (+, -, *, /), and paretnheses. It converts infix expressions to postfix notation and evaluates the result, while handlnig common syntax errors.

Input Specifications

Input expressions may include spaces. The program validates balanced parentheses and operator placement before conversion and evaluation.

Output Specifications

For valid expressions: Output postfix notation followed by the evaluated result. For errors: Output "ERROR:缺少括号" (missing parentheses) or "ERROR:表达式缺操作数" (missing opearnds).

Example Execution

Input: 5*(8-(3+2))
Output:
5832+-*
15

Implementation

#include <iostream>
#include <stack>
#include <string>
using namespace std;

string removeSpaces(string input) {
    string cleaned;
    for (char c : input) {
        if (c != ' ') cleaned += c;
    }
    return cleaned;
}

bool validateParentheses(string expr) {
    int balance = 0;
    for (char c : expr) {
        if (c == '(') balance++;
        else if (c == ')') balance--;
    }
    return balance == 0;
}

bool validateOperators(string expr) {
    for (int i = 0; i < expr.length(); i++) {
        if (expr[i] == '+' || expr[i] == '-' || expr[i] == '*' || expr[i] == '/') {
            if (i == 0 || i == expr.length() - 1) return false;
            if (expr[i - 1] == '+' || expr[i - 1] == '-' || 
                expr[i - 1] == '*' || expr[i - 1] == '/') {
                return false;
            }
        }
    }
    return true;
}

int precedence(char op) {
    return (op == '*' || op == '/') ? 2 : 1;
}

string infixToPostfix(string infix) {
    stack<char> opStack;
    string postfix;

    for (char c : infix) {
        if (isdigit(c)) {
            postfix += c;
        } else if (c == '(') {
            opStack.push(c);
        } else if (c == ')') {
            while (!opStack.empty() && opStack.top() != '(') {
                postfix += opStack.top();
                opStack.pop();
            }
            opStack.pop();
        } else {
            while (!opStack.empty() && opStack.top() != '(' && 
                   precedence(c) <= precedence(opStack.top())) {
                postfix += opStack.top();
                opStack.pop();
            }
            opStack.push(c);
        }
    }

    while (!opStack.empty()) {
        postfix += opStack.top();
        opStack.pop();
    }
    return postfix;
}

int calculate(int a, int b, char op) {
    switch (op) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return a / b;
        default: return 0;
    }
}

int evaluatePostfix(string postfix) {
    stack<int> numStack;
    for (char c : postfix) {
        if (isdigit(c)) {
            numStack.push(c - '0');
        } else {
            int b = numStack.top(); numStack.pop();
            int a = numStack.top(); numStack.pop();
            numStack.push(calculate(a, b, c));
        }
    }
    return numStack.top();
}

int main() {
    string input;
    getline(cin, input);
    string cleaned = removeSpaces(input);

    if (!validateParentheses(cleaned)) {
        cout << "ERROR:缺少括号";
        return 0;
    }

    if (!validateOperators(cleaned)) {
        cout << "ERROR:表达式缺操作数";
        return 0;
    }

    string postfix = infixToPostfix(cleaned);
    cout << postfix << endl;
    cout << evaluatePostfix(postfix);
    return 0;
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.