Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)
Paste
Pasted as C by registered user r_i_nahian ( 12 years ago )
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#define MAX 50
enum operators
{
multiply=0, divide=0, add=1, subtract=1, leftparen=2
}op;
int push(char[], char, int);
int pop(char[], int*);
int checkStack(char[],int*,char[],int);
void main()
{
char infix[MAX]="", postfix[MAX]="", Stack[MAX]="", element;
int p=-1,i=0,disp=0,top=-1,oper=0;
//Get the infix expression as input
puts("Enter the infix expression with single character variables and operators");
gets(infix);
top=push(Stack,'(',top);
//Insert a dummy left parenthesis to write all the remaining operators in the stack
for(i=0;infix[i] != '\0';i++)//For each character in the infix expression
{
if(isalpha(infix[i]))//Write operands in the postfix expression
{
postfix[++p] = infix[i];
}
else//If operator
{
switch(infix[i])
{
case '*':
op = multiply;
oper=1;
break;
case '/':
op = divide;
oper=1;
break;
case '+':
op = add;
oper=1;
break;
case '-':
op = subtract;
oper=1;
break;
case '(':
top=push(Stack,'(',top);//Push left parenthesis into the stack
break;
case ')':
while((element=pop(Stack,⊤)) != '(')
//Pop from stack and write to postfix expression till u encounter a left parenthesis
{
postfix[++p] = element;
}//while
//Delete the left parenthesis
break;
}//switch
if(oper==1)//Perform only for operators
{
//Check with the operator at the top of the stack
p=checkStack(Stack,⊤,postfix,p);
top=push(Stack,infix[i],top);//Push operator to the stack
oper=0;
}
}//else
}//for
while((element=pop(Stack,⊤)) != '(' )
//Use the first pushed '(' to pop the remaining elements in the stack
{
postfix[++p] = element;
}//while
for(disp=0;disp<=p;disp++)//Print the postfix expression
putchar(postfix[disp]);
getch();
}
int checkStack(char Stack[],int *top, char postfix[], int p)
{
enum operators opStack;
do
{
switch(Stack[(*top)])
{
case '*':
opStack = multiply;
break;
case '/':
opStack = divide;
break;
case '+':
opStack = add;
break;
case '-':
opStack = subtract;
break;
case '(':
opStack = leftparen;
}//switch
if(op >= opStack)
//If the operator at the top of the stack is of equal or higher precedence
postfix[++p] = pop(Stack,top);//Pop and write to the postfix expression
}while(op >= opStack);
return(p);
}
int push(char Stack[],char element,int top)
{
if(top == MAX-1)
printf("Stack Overflow");
else
{
Stack[++top] = element;
}
return(top);
}
int pop(char Stack[],int *top)
{
int element;
if((*top) == -1)
{
printf("Stack Underflow");
element = -999;
}
else
element = Stack[(*top)--];
return(element);
}
Revise this Paste