infix to prefix

Run Settings
LanguageC++
Language Version
Run Command
#include <iostream> #include<ctype.h> using namespace std; #define Max 20 int priority(char ch); class InfixToPostfix { }; class Stack{ char stack[Max]; public: int top = 0; void push(char value) { if(top == Max-1) { cout<<"Stack Overflow"<<"\n"; return; } top++; stack[top] = value; } char pop() { if(top == -1) { cout<<"Stack Underflow"<<"\n"; return -1; } char value = stack[top]; top--; return value; } char peek() { return stack[top]; } }; int priority(char ch) { if(ch=='^') return 3; if(ch == '*' || ch =='%' || ch == '/' ) return 2; if(ch == '+' || ch == '-') return 1; return 0; } int main() { char infix[] = "((A+B)*(C-D))+(F-G)"; // for(int i=0;i<10;i++) // cout<<infix[i]; char reverseinfix[20]; for(int i=0;i<20;i++) { if(infix[19-i]==')'){ reverseinfix[i] = '(';continue;} if(infix[19-i]=='('){ reverseinfix[i] =')'; continue;} reverseinfix[i] = infix[19-i]; } for(int i=0;i<20;i++) cout<<reverseinfix[i]; cout<<"\n"; char postfix[20]; char prefix[20]; int p_index = 0; Stack src; for(int i=0;i<20;i++) { if(reverseinfix[i]=='(') { src.push(reverseinfix[i]); continue; } if(reverseinfix[i]==')') { char ch = src.pop(); while(ch != '(' && src.top!=-1) { postfix[p_index]= ch; p_index++; ch = src.pop(); } continue; } if(reverseinfix[i]=='+'||reverseinfix[i]=='-'||reverseinfix[i]=='*'||reverseinfix[i]=='/'||reverseinfix[i]=='%'||reverseinfix[i]=='^') { if(src.top!=-1) { char op = src.pop(); while(priority(op)>=priority(reverseinfix[i]) && src.top!=-1) { postfix[p_index]= op; p_index++; op = src.pop(); } src.push(op); src.push(reverseinfix[i]); } else { src.push(reverseinfix[i]); } continue; } if(isdigit(reverseinfix[i]) || isalpha(reverseinfix[i])){ postfix[p_index]= reverseinfix[i]; p_index++; continue; } } while(src.top!=-1) { char ch = src.pop(); postfix[p_index] = ch; p_index++; } for(int i=0;i<p_index;i++) { prefix[i] = postfix[p_index-i]; } for(int i=0;i<p_index;i++) { cout<<prefix[i]; } return 0; }
Editor Settings
Theme
Key bindings
Full width
Lines