Last active
October 12, 2020 04:17
-
-
Save shemul/329a15fda7d217a61358 to your computer and use it in GitHub Desktop.
Infix_to_Prefix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# include <stdio.h> | |
# include <iostream> | |
# include <string.h> | |
# define MAX 20 | |
using namespace std; | |
int top=-1; | |
char stack[MAX]; | |
void reverse(char array[30]) | |
{ | |
int i,j; | |
char temp[100]; | |
for (i=strlen(array)-1,j=0;i+1!=0;--i,++j) { | |
temp[j]=array[i]; | |
} | |
temp[j]='\0'; | |
strcpy(array,temp); | |
} | |
int isOperator(char symbol) { | |
switch(symbol) { | |
case '+': | |
case '-': | |
case '*': | |
case '/': | |
case '^': | |
case '$': | |
case '&': | |
case '(': | |
case ')': | |
return 1; | |
break; | |
default: | |
return 0; | |
} | |
} | |
char pop() { | |
char a; | |
a=stack[top]; | |
top--; | |
return a; | |
} | |
//---------------------------------- | |
void push(char symbol) { | |
top++; | |
stack[top]=symbol; | |
} | |
//------------------------------------------ | |
int prcd(char symbol) | |
{ | |
switch(symbol) { | |
case '+': | |
case '-': | |
return 2; | |
break; | |
case '*': | |
case '/': | |
return 4; | |
break; | |
case '$': | |
case '^': | |
return 6; | |
break; | |
case '#': | |
case '(': | |
case ')': | |
return 1; | |
break; | |
} | |
} | |
//-------- | |
void infixtoprefix(char infix[20],char prefix[20]) { | |
int i,j=0; | |
char symbol; | |
push('#'); // or stack[++k]='#' | |
reverse(infix); | |
cout << "After reverse the Infix expression : " << infix <<endl; | |
for (i=0;i<strlen(infix);i++) { | |
symbol=infix[i]; | |
if (isOperator(symbol)==0) { | |
prefix[j]=symbol; | |
j++; | |
} else { | |
if (symbol==')') { | |
push(symbol); | |
} else if(symbol == '(') { | |
while (stack[top]!=')') { | |
prefix[j]=pop(); | |
j++; | |
} | |
pop(); | |
} else { | |
if (prcd(stack[top])<=prcd(symbol)) { | |
push(symbol); | |
} else { | |
while(prcd(stack[top])>=prcd(symbol)) { | |
prefix[j]=pop(); | |
j++; | |
} | |
push(symbol); | |
} | |
//end for else | |
} | |
} | |
//end for else | |
} | |
//end for for | |
while (stack[top]!='#') { | |
prefix[j]=pop(); | |
j++; | |
} | |
prefix[j]='\0'; | |
} | |
////-------------------------------------------------------- | |
main() | |
{ | |
char infix[20],prefix[20],temp; | |
printf("Enter infix operation: "); | |
cin >> infix; | |
infixtoprefix(infix,prefix); | |
reverse(prefix); | |
cout<<prefix ; | |
} | |
//-------------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this code might has some compilation error on different range of compiler limitation , please feel free to reply if you have any touble 👍