একটি গাণিতিক অভিব্যক্তি সমাধানের জন্য, আমাদের উপসর্গ বা পোস্টফিক্স ফর্ম প্রয়োজন। ইনফিক্সকে পোস্টফিক্সে রূপান্তর করার পরে, সঠিক উত্তর খুঁজতে আমাদের পোস্টফিক্স মূল্যায়ন অ্যালগরিদম প্রয়োজন৷
এখানেও পোস্টফিক্স এক্সপ্রেশন সমাধান করতে স্ট্যাক ডেটা স্ট্রাকচার ব্যবহার করতে হবে।
পোস্টফিক্স এক্সপ্রেশন থেকে, যখন কিছু অপারেন্ড পাওয়া যায়, সেগুলিকে স্ট্যাকের মধ্যে পুশ করে। যখন কিছু অপারেটর পাওয়া যায়, স্ট্যাক থেকে দুটি আইটেম পপ করা হয় এবং অপারেশনটি সঠিক ক্রমানুসারে সঞ্চালিত হয়। এর পরে, ফলাফলটি ভবিষ্যতে ব্যবহারের জন্য স্ট্যাকের মধ্যেও পুশ করা হয়। সম্পূর্ণ অভিব্যক্তি সম্পূর্ণ করার পরে, চূড়ান্ত ফলাফলটি স্ট্যাকের শীর্ষে সংরক্ষণ করা হয়।
ইনপুট এবং আউটপুট
Input: Postfix expression: 53+62/*35*+ Output: The result is: 39
অ্যালগরিদম
postfixEvaluation(postfix)
ইনপুট: মূল্যায়নের জন্য পোস্টফিক্স এক্সপ্রেশন।
আউটপুট: পোস্টফিক্স ফর্ম মূল্যায়ন করার পরে উত্তর দিন।
Begin for each character ch in the postfix expression, do if ch is an operator ⨀ , then a := pop first element from stack b := pop second element from the stack res := b ⨀ a push res into the stack else if ch is an operand, then add ch into the stack done return element of stack top End
উদাহরণ
#include<iostream>
#include<cmath>
#include<stack>
using namespace std;
float scanNum(char ch) {
int value;
value = ch;
return float(value-'0'); //return float from character
}
int isOperator(char ch) {
if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^')
return 1; //character is an operator
return -1; //not an operator
}
int isOperand(char ch) {
if(ch >= '0' && ch <= '9')
return 1; //character is an operand
return -1; //not an operand
}
float operation(int a, int b, char op) {
//Perform operation
if(op == '+')
return b+a;
else if(op == '-')
return b-a;
else if(op == '*')
return b*a;
else if(op == '/')
return b/a;
else if(op == '^')
return pow(b,a); //find b^a
else
return INT_MIN; //return negative infinity
}
float postfixEval(string postfix) {
int a, b;
stack<float> stk;
string::iterator it;
for(it=postfix.begin(); it!=postfix.end(); it++) {
//read elements and perform postfix evaluation
if(isOperator(*it) != -1) {
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
stk.push(operation(a, b, *it));
}else if(isOperand(*it) > 0) {
stk.push(scanNum(*it));
}
}
return stk.top();
}
main() {
string post = "53+62/*35*+";
cout << "The result is: "<<postfixEval(post);
} আউটপুট
The result is: 39