Selasa, 18 Mei 2010

Infix to Prefix - Infix to Postfix

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 10

char stack[MAX];
int top = -1;
char pop()
{
char a;
a=stack[top];
top--;
return a;
}

void push(char item)
{
top++;
stack[top]=item;
}

void clear()
{
for(int c=0; c<25; c++)
printf("\n");
}


int prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 2;
case '*':
case '/':
return 4;
case '^':
case '$':
return 6;
case '(':
case ')':
case '#':
return 1;
}
}

int isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
return 1;
default:
return 0;
}
}


void convertip(char infix[],char prefix[])
{
int i,symbol,j=0;
char test[MAX];

infix=strrev(infix);
stack[++top]='#';

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(symbol)>prcd(stack[top]))
{
push(symbol);
}
else
{
while(prcd(symbol)<=prcd(stack[top]))
{
prefix[j]=pop();
j++;
}
push(symbol);
}
}
}
}

while(stack[top]!='#')
{
prefix[j]=pop();
j++;
}
prefix[j]='\0';
prefix=strrev(prefix);
}


void convertipo(char infix[],char postfix[])
{
int i,symbol,j=0;
char test[MAX];

stack[++top]='#';

for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(isoperator(symbol)==0)
{
postfix[j]=symbol;
j++;
}
else
{
if(symbol=='(')
{
push(symbol);
}
else if(symbol==')')
{
while(stack[top]!='(')
{
postfix[j]=pop();
j++;
}
pop();
}
else
{
if(prcd(symbol)>prcd(stack[top]))
{
push(symbol);
}
else
{
while(prcd(symbol)<=prcd(stack[top]))
{
postfix[j]=pop();
j++;
}
push(symbol);
}
}
}
}

while(stack[top]!='#')
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';

}

int main()
{
int choice;
char infix[20],prefix[20],postfix[20];
do
{
clear();
printf(" INFIX->PREFIX INFIX->POSTFIX CONVERTER\n");
printf(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\n");

printf(" 1. Infix to Prefix\n");
printf(" 2. Infix to Postfix\n");
printf(" 3. Exit\n");

printf("\n >> Input choice : ");
scanf("%d", &choice); fflush(stdin);

switch(choice)
{
case 1 :
{
printf("\n\n\n Input An Infix Notation [a ('+','-','*','/') b ('+','-','*','/') c]: ");
gets(infix); fflush(stdin);
convertip(infix,prefix);
printf("\n\n\n\n Prefix : ");
puts(prefix); fflush(stdin);
getchar();
break;
}
case 2 :
{
printf("\n\n\n Input An Infix Notation [a ('+','-','*','/') b ('+','-','*','/') c]: ");
gets(infix); fflush(stdin);
convertipo(infix,postfix);
printf("\n\n\n\n Postfix : ");
puts(postfix); fflush(stdin);
getchar();
break;
}
}
}while(choice!=3);
}