Conversion from Infix to Postfix in C

Only available on StudyMode
  • Topic: Void
  • Pages : 4 (279 words )
  • Download(s) : 141
  • Published : March 2, 2013
Open Document
Text Preview
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<string.h>
#include<ctype.h>
#define max 30

struct stack
{
char opstack[max];
int tos;
};

void push(struct stack *,char);
char pop(struct stack *);
int prece(char );

void main()
{
int i,j=0,k,l;
char ch,infix[max], postfix[max];
stack pq;
pq.tos=-1;

A:
clrscr();
printf("\nEnter the infix string:\t");
gets(infix);

for(i=0;infix[i]!='\0';i++)
{
if (infix[i]=='(')
push(&pq,infix[i]);
else if (isalpha(infix[i]))
{postfix[j]=infix[i];
j++; }
else if (infix[i]=='+'||infix[i]=='-'||infix[i]=='/'||infix[i]=='$'||infix[i]=='*') {
if(pq.tos!=-1 && prece(pq.opstack[pq.tos])>=prece(infix[i])) {ch=pop(&pq);
postfix[j]=ch;
j++;
}
push(&pq,infix[i]);
}
else if (infix[i]==')')
{
for(;pq.opstack[pq.tos]=='(';)
l=pq.tos;
for(k=-1;k<l;k++)
{
postfix[j]=pop(&pq);
j++;
}
}
else
{
printf("\nError: Your infix contains invalid characters. Press any key to try again.\t"); getch();
goto A;
}
}
while (pq.opstack[pq.tos]!=NULL)
{
postfix[j]=pop(&pq);
j++;
}
postfix[j]='\0';
for(i=0;i<j;i++)
{
if(postfix[i]!='(')
printf("%c",postfix[i]);
}
getch();
}

int prece(char a)
{
int q;
switch (a)
{
case '$':
q=4;
break;

case '*': case '/':
q=3;
break;

case '+': case '-':
q=2;
break;

case '(':
q=1;
}
return(q);
}

void push(struct stack *ps,char b)
{
ps->tos++;
ps->opstack[ps->tos]=b;
}

char pop(struct stack *ps)
{
char p;
p=ps->opstack[ps->tos];
ps->tos--;
return(p);
}
tracking img