गणितीय व्यंजक को हल करने के लिए, हमें उपसर्ग या पोस्टफिक्स फॉर्म की आवश्यकता होती है। इंफिक्स को पोस्टफिक्स में बदलने के बाद, हमें सही उत्तर खोजने के लिए पोस्टफिक्स मूल्यांकन एल्गोरिदम की आवश्यकता होती है।
यहां भी हमें पोस्टफिक्स एक्सप्रेशन को हल करने के लिए स्टैक डेटा संरचना का उपयोग करना होगा।
पोस्टफ़िक्स एक्सप्रेशन से, जब कुछ ऑपरेंड मिलते हैं, तो उन्हें स्टैक में धकेल दिया जाता है। जब कुछ ऑपरेटर मिल जाता है, तो स्टैक से दो आइटम पॉप हो जाते हैं और ऑपरेशन सही क्रम में किया जाता है। उसके बाद, परिणाम को भविष्य में उपयोग के लिए स्टैक में भी धकेल दिया जाता है। पूरे एक्सप्रेशन को पूरा करने के बाद फाइनल रिजल्ट भी स्टैक टॉप में स्टोर हो जाता है।
इनपुट और आउटपुट
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