This commit is contained in:
louiscklaw
2025-01-31 21:27:38 +08:00
parent 8cce226ca9
commit ca0eb416dd
90 changed files with 4082 additions and 0 deletions

View File

@@ -0,0 +1,103 @@
#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::string postfix = infixToPostfix(infix);
std::cout << "Postfix expression: " << postfix << std::endl;
int result = evaluatePostfix(postfix);
std::cout << "Result: " << result << std::endl;
return 0;
}