C PROGRAMMINGDATA STRUCTURES

infix to postfix and infix to prefix conversion

infix to postfix and infix to prefix conversion

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

struct stack
{
char data;
struct stack *link;
};

struct stack *top=NULL;

void push(char c)
{
struct stack *temp;
temp=(struct stack *)malloc(sizeof(struct stack *));
temp->data=c;
temp->link=top;
top=temp;
}

char pop()
{
char data;
data=top->data;
top=top->link;
return data;
}

char peek()
{
return top->data;
}
int precedence(char c)
{
if(c=='^')
return 3;
if(c=='*' || c=='/')
return 2;
if(c=='+' || c=='-')
return 1;
else
return 0;
}


void infix2post(char infix[])
{
int i=0;
while(infix[i]!='')
{
//check operand --> send operand to output
if((infix[i]>='a' && infix[i]<='z')||(infix[i]>='A' && infix[i]<='Z'))
printf("%c",infix[i]);
else if(infix[i]=='(') //if ( push to stack
push(infix[i]);
else if(infix[i]==')') // continously pop untill ) is encountered
{
while(peek()!='(')
{
printf("%c",pop());
}
pop();
}
else // if operator is encountered
{
if(precedence(infix[i])>precedence(peek()))
push(infix[i]);
else
{
while(precedence(infix[i])<=precedence(peek()))
printf("%c",pop());
push(infix[i]);
}
}
i++;
}
}

void infix2prefix(char infix[])
{
int i=0,j;
char prefix[20];
char c;
while(infix[i]!='')
{
c=infix[i++];
if(c=='(')
push(')');
else if(c==')')
push('(');
else
push(c);
}
i=0;
j=0;
while(top!=NULL)
infix[i++]=pop();
infix[i]='';
i=0;
while(infix[i]!='')
{
//check operand --> send operand to output
if((infix[i]>='a' && infix[i]<='z')||(infix[i]>='A' && infix[i]<='Z'))
prefix[j++]=infix[i];
else if(infix[i]=='(') //if ( push to stack
push(infix[i]);
else if(infix[i]==')') // continously pop untill ) is encountered
{
while(peek()!='(')
{
prefix[j++]=pop();
}
pop();
}
else // if operator is encountered
{
if(precedence(infix[i])>precedence(peek()))
push(infix[i]);
else
{
while(precedence(infix[i])<=precedence(peek()))
prefix[j++]=pop();
push(infix[i]);
}
}
i++;
}
prefix[j]='';

printf("%s",strrev(prefix));
}

void main()
{
char expression[100];
int choice;
do
{
printf("nn*********Menu************nn");
printf("Press 1 for Infix to Postfix conversionnn");
printf("press 2 for Infix to Prefix conversionnn");
printf("any other key to exitn");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter an infix Epression : ");
scanf("%s",expression);
printf("Postfix Expression n");
infix2post(expression);
//printf("n Result after expression evaluation is : %d",infix2post(postfix));
break;

case 2:
printf("nEnter Infix Expressionn");
scanf("%s",expression);
printf("prefix Expression n");
infix2prefix(expression);
//printf("ninfix after conversion of prefix is: %d", infix2prefix(prefix));
break;

default:
exit(0);
}
}while(choice);

getch();
}

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button