You are on page 1of 3

#include<stdio.

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

#define TRUE 1
#define FALSE 0
#define STACKSIZE 20

struct Stack
{
int top;
int item[STACKSIZE];
};

int prcd(char op1,char op2);


int priority(char op);
void push(struct Stack *ps,char ch);
int pop(struct Stack *ps);
int empty(struct Stack *ps);
int peek(struct Stack *ps);

int main()
{
struct Stack s;
char infix[100];
char postfix[100];
char ch,topsymb;
printf("enter the infix expression\n");

gets(infix);
int i,j=0;
s.top=-1;
for(i=0;infix[i]!='\0';i++)
{
ch=infix[i];
if(isdigit(ch)||isalpha(ch)){
postfix[j++]=ch;}
else
{
while(!empty(&s) && prcd(peek(&s),ch))
{
topsymb=pop(&s);
postfix[j++]=topsymb;
}
if(ch!=')')
push(&s,ch);
else
topsymb=pop(&s);

}
}
while(!empty(&s))
{
topsymb=pop(&s);
postfix[j++]=topsymb;
}
postfix[j]='\0';
int k;
for(k=0;k<j;k++)
{
if(postfix[k]=='(' || postfix[k]==')')
{
printf("unequal brackets\n");
exit(0);
}
}
printf("the postfix expression:%s\n",postfix);
}

int peek(struct Stack *ps) //peek function


{
return ps->item[ps->top];
}

int empty(struct Stack *ps) //empty function


{
if(ps->top==-1)
return TRUE;
else
return FALSE;
}

int pop(struct Stack *ps) //pop function


{
return(ps->item[ps->top--]);
}

void push(struct Stack *ps, char ch) //push function


{
ps->item[++(ps->top)]=ch;
}

int prcd(char op1,char op2) //prcd function


{
if(op1=='(' && op2==')')
return FALSE;
if(op1=='(')
return FALSE;
if(op2=='(' && op1!=')')
return FALSE;
if(op2==')' && op1!='(')
return TRUE;
if(priority(op1)==priority(op2) && priority(op2)==3)
return FALSE;
if(priority(op1)>=priority(op2))
return TRUE;
return FALSE;
}

int priority(char op) //priority function


{
int precedence;
switch(op)
{
case '$':precedence=3;
break;
case '*':
case '/':precedence=2;
break;
case '+':
case '-':precedence=1;
break;
case ')':
case '(':precedence=0;
break;
}
return precedence;
}

You might also like