3. Write a program for evaluating the value for a given postfix expression using stack data structure.
a) Infix to Postfix
b)Prefix to Infix
#include<iostream>
#include <string>
#include <stack>
using namespace std;
int prototype(char c) {
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
void InToPos(string s) {
stack<char> st; //For stack operations, we are using C++ built in stack
string result;
for (int i = 0; i < s.length(); i++) {
char c = s[i];
// If the scanned character is
// an operand, add it to output string.
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
result += c;
// If the scanned character is an
// ‘(‘, push it to the stack.
else if (c == '(')
st.push('(');
else if (c == ')') {
while (st.top() != '(')
{
result += st.top();
st.pop();
}
st.pop();
}
else {
while (!st.empty() && prototype(s[i]) <= prototype(st.top())) {
result += st.top();
st.pop();
}
st.push(c);
}
}
while (!st.empty()) {
result += st.top();
st.pop();
}
cout << result << endl;
}
bool isOp(char ch)
{
return (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z');
}
string PosToIn(string exp)
{
stack<string> s;
for (int i = 0; exp[i] != '\0'; i++)
{
if (isOp(exp[i]))
{
string op(1, exp[i]);
s.push(op);
}
else
{
string op1 = s.top();
s.pop();
string op2 = s.top();
s.pop();
s.push("(" + op2 + exp[i] +
op1 + ")");
}
}
return s.top();
}
int main() {
bool quit = false;
while (!quit)
{
cout << "\nMENU\n";
cout << "1 -Postfix to Infix\n";
cout << "2 -Infix to Postfix\n";
cout << "3 -Exit\n";
int cmd;
cin >> cmd;
switch (cmd)
{
case 1:
{
cout << "Please enter expression: ";
string exp;
cin >> exp;
InToPos(exp);
break;
}
case 2:
{
cout << "Please enter expression: ";
string exp;
cin >> exp;
cout<<PosToIn(exp);
break;
}
case 3:
{
quit = true;
break;
}
default:
break;
}
}
return 0;
}
Comments
Leave a comment