Files
004_comission/marissa.sam/task2/temp/_draft/helloworld copy 3.cpp
louiscklaw ca0eb416dd update,
2025-01-31 21:27:38 +08:00

122 lines
3.1 KiB
C++

#include <iostream>
#include <stack>
#include <string>
#include <cctype>
#include <map>
// Function to convert infix expression to postfix expression
std::string infixToPostfix(const std::string &infix)
{
std::stack<char> s;
std::string postfix;
std::map<char, int> precedence = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'(', 0}};
for (char c : infix)
{
if (std::isalnum(c))
{ // 1. if operand, add to postfix
postfix += c;
}
else if (c == '(')
{ // 2. if '(', push to stack
s.push(c);
}
else if (c == ')')
{ // 3. if ')', pop until '('
while (!s.empty() && s.top() != '(')
{
postfix += s.top();
s.pop();
}
if (!s.empty())
s.pop(); // pop '('
}
else
{ // 4. if operator, pop operators with greater or equal precedence
while (!s.empty() && precedence[c] <= precedence[s.top()])
{
postfix += s.top();
s.pop();
}
s.push(c); // push current operator
}
}
// 5. pop remaining operators
while (!s.empty())
{
postfix += s.top();
s.pop();
}
return postfix;
}
// Function to evaluate postfix expression
int evaluatePostfix(const std::string &postfix)
{
std::stack<int> s;
for (char c : postfix)
{
if (std::isdigit(c))
{ // 1. if operand, push to stack
s.push(c - '0');
}
else
{ // 2. if operator, pop two operands, evaluate and push result
int op2 = s.top();
s.pop();
int op1 = s.top();
s.pop();
switch (c)
{
case '+':
s.push(op1 + op2);
break;
case '-':
s.push(op1 - op2);
break;
case '*':
s.push(op1 * op2);
break;
case '/':
s.push(op1 / op2);
break;
}
}
}
return s.top(); // 3. result is the only element in stack
}
int main()
{
std::string infix;
// std::cout << "Enter an arithmetic expression: ";
// std::getline(std::cin, infix);
std::cout << "e.g. 1 1+4*5" << std::endl;
infix = "1+4*5";
std::string postfix = infixToPostfix(infix);
std::cout << "Postfix expression: " << postfix << std::endl;
int result = evaluatePostfix(postfix);
std::cout << "Result: " << result << std::endl;
std::cout << "e.g. 2 (1+4)*5" << std::endl;
infix = "(1+4)*5";
postfix = infixToPostfix(infix);
std::cout << "Postfix expression: " << postfix << std::endl;
result = evaluatePostfix(postfix);
std::cout << "Result: " << result << std::endl;
std::cout << "e.g. 3 1+4-5" << std::endl;
infix = "1+4-5";
postfix = infixToPostfix(infix);
std::cout << "Postfix expression: " << postfix << std::endl;
result = evaluatePostfix(postfix);
std::cout << "Result: " << result << std::endl;
return 0;
}