Assignment 2
Assignment 2
expression to a postfix expression and then evaluate the postfix expression to print the result:
#include <iostream>
#include <stack>
#include <string>
return 1;
return 2;
return 0;
string postfix;
stack<char> stack;
if (isalnum(ch))
postfix += ch;
stack.push(ch);
postfix += stack.top();
stack.pop();
} else {
postfix += stack.top();
stack.pop();
stack.push(ch);
while (!stack.empty()) {
postfix += stack.top();
stack.pop();
return postfix;
stack<int> stack;
if (isdigit(ch))
stack.push(ch - '0');
else {
if (ch == '+')
stack.push(operand1 + operand2);
stack.push(operand1 - operand2);
stack.push(operand1 * operand2);
return stack.top();
}
int main() {
evaluateExpression(infixExpression);
return 0;
This C++ code converts a given infix expression to a postfix expression using the shunting-
yard algorithm and then evaluates the postfix expression using a stack-based approach.
Finally, it prints the postfix expression and the result of the evaluation. You can replace the
infixExpression variable with any valid infix expression to test the code.