Kumar-laxmi / Algorithms

A Repository for algorithms in C, C++, Python and Java
Apache License 2.0
309 stars 372 forks source link

Reverse Polish Notation #1706

Closed Devchawla2608 closed 3 months ago

Devchawla2608 commented 12 months ago

Is your feature request related to a problem? Please describe. Reverse Polish Notation also known as postfix notation

1.) Create an empty stack to hold operands. 2.) Read the expression from left to right. 3.) If the element is an operand, push it onto the stack. 4.) If the element is an operator, pop the required number of operands from the stack, perform the operation, and push the result back onto the stack. 5.) After reading the entire expression, the final result is left on the stack.

image

Devchawla2608 commented 12 months ago

@Kumar-laxmi please assign this to me under SSOC'23. I'm ready to contribute in all 4 languages

rajchaudhary99 commented 11 months ago

//Reverse Polish Notation in c++ int evaluateRPN(const string& expression) { stack operands;

stringstream ss(expression);
string token;

while (getline(ss, token, ' ')) {
    if (isdigit(token[0])) {

        operands.push(stoi(token));
    } else {

        int operand2 = operands.top();
        operands.pop();
        int operand1 = operands.top();
        operands.pop();

        if (token == "+") {
            operands.push(operand1 + operand2);
        } else if (token == "-") {
            operands.push(operand1 - operand2);
        } else if (token == "*") {
            operands.push(operand1 * operand2);
        } else if (token == "/") {
            operands.push(operand1 / operand2);
        }
    }
}

return operands.top();

}

github-actions[bot] commented 3 months ago

Stale issue message