In: Computer Science
this is my code I want the opposite i want to convert a postfix expression to infix expression
#include <iostream>
#include <string>
#define SIZE 50
using namespace std;
// structure to represent a stack
struct Stack {
char s[SIZE];
int top;
};
void push(Stack *st, char c) {
st->top++;
st->s[st->top] = c;
}
char pop(Stack *st) {
char c = st->s[st->top];
st->top--;
//(A+B)*(C+D)
return c;
}
/* function to check whether a character is an operator or not.
this function returns 1 if character is operator else returns 0 */
int isOperator(char c) {
switch (c)
{
case '^':
case '+':
case '-':
case '*':
case '/':
case '%':
return 1;
default:
return 0;
}
}
/* function to assign precedence to operator.
In this function we assume that higher integer value means higher precedence */
int precd(char c) {
switch (c)
{
case '^':
return 3;
case '*':
case '/':
case '%':
return 2;
case '+':
case '-':
return 1;
default:
return 0;
}
}
//function to convert infix expression to postfix expression
string infixToPostfix(Stack *st, string infix) {
string postfix = "";
for(int i=0; i<infix.length(); i++)
{
if(isOperator(infix[i])==1)
{
while(st->top!=-1 && precd(st->s[st->top]) >= precd(infix[i]))
postfix += pop(st);
push(st,infix[i]);
}
else if(infix[i] == '(')
push(st,infix[i]);
else if(infix[i] == ')')
{
while(st->top!=-1 && st->s[st->top] != '(')
postfix += pop(st);
pop(st);
}
else
postfix += infix[i];
}
while(st->top != -1)
postfix += pop(st);
return postfix;
}
int main() {
Stack st;
st.top = -1;
string infix;
cout << "Enter an infix expression: ";
getline(cin, infix);
cout << "Postfix expression is: " << infixToPostfix(&st, infix);
return 0;
}
#include <bits/stdc++.h>
using namespace std;
bool isOperand(char x) {
return (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z');
}
string PostfixToInfix(string postfix) {
stack<string> infix;
for (int i=0; postfix[i]!='\0'; i++) {
if (isOperand(postfix[i])) {
string op(1, postfix[i]);
infix.push(op);
} else {
string op1 = infix.top();
infix.pop();
string op2 = infix.top();
infix.pop();
infix.push("{"+op2+postfix[i]+op1 +"}");
}
}
return infix.top();
}
int main() {
string infix, postfix;
cout<<"Enter a POSTFIX expression:<< postfix << endl;
cin>> postfix;
cout<<"POSTFIX Expression: "<< postfix << endl;
infix = PostfixToInfix(postfix);
cout<< endl << "INFIX Expression: " << infix;
return 0;
}