C program to convert Infix to Prefix using Stack data structure
Simple C program to convert Infix to Prefix using Stack data structure
Code:
#include<stdio.h>#include<string.h>
#include<ctype.h>
#include<conio.h>
char steck[50];
int top=-1;
void push(char ele){
top++;
steck[top]=ele;
}
char pop(){
return (steck[top--]);
}
int isoperator(char ele){
if (ele=='^' ||ele=='#' || ele=='/' || ele=='+' || ele=='-'){
return 1;
}
else{
return 0;
}
}
int pre(char ele)
{
if (ele =='#') {
return 4;
}
else if (ele=='*' || ele=='/'){
return 3;
}
else if (ele=='+' || ele =='-'){
return 2;
}
else return 0;
}
void main(){
char infix[20],postfix[20];
int i,j=0;
char c;
clrscr();
printf("Enter the String: ");
scanf("%s",infix);
strrev(infix);
printf("%s",infix);
// printf("%d",strlen(infix));
for (i=0;i< (strlen(infix)) ;i++){
// c=infix[i];
if(isoperator(infix[i])){
if (top==-1){
push(infix[i]);
}
else{
while (pre(infix[i])<=pre(steck[top])){
postfix[j++]=pop();
}
push(infix[i]);
}
}
else{
postfix[j++]=infix[i];
}
}
while (top!=-1){
postfix[j++]=pop();
}
postfix[j]='\0';
printf("\n%s",strrev(postfix) );
getch();
}
Comments
Post a Comment