INFIX TO POSTFIX
A+B*C+D-->>ABC*+D+
ALGORITHM FOR INFIX TO POSTFIX CONVERSION:
- Create an empty stack and an empty postfix output string/stream.
- Scan the infix input string/stream left to right.
- If the current input taken is an operand simply append it to the output string.
- If the current taken is an operator,pop off all operators that have equal or higher precedence and append them to the output string . The order of popping is the order in the output.
- If the current input token is " ( " push it into the stack.
- If the current input token is " ) " pop off all operators and append them to string until a " ( "is popped discard the " (" .
- If the end of input string is found ,pop all operators and append them to the output string.
PROGRAM FOR INFIX TO POSTFIX CONVERSION IN CPP:
#include<iostream.h>
#include<conio.h>
#include<ctype.h>
struct node //STRUCTURE
{
char data; //DATA PART
struct node *next; //NEXT IS A POINTER POINTING TO NEXT NODE
}*top = NULL;
int prece(char token);
class stack //CLASS WITH NAME STACK
{
public:
void push(char x) //INPUT DATA INTO NODE\STACK
{
struct node *p;
p=new node;
p->data=x;
p->next=top;
top=p;
}
char pop() //REMOVE DATA FROM STACK
{
char x;
x=top->data;
top=top->next;
return x;
}
void display() //DISPLAY TOTAL NO DATA VALUE IN STACK NODE
{
struct node *p;
p=top;
while(p!=NULL)
{
cout<<"\n"<<p->data <<"\n";
p=p->next;
}
}
char infix_postfix(char postfix[30],char infix[30]);
char top1()
{
return top->data;
}
int empty() //TO CHECK STACK IS EMPTY OR NOT
{
if(top==NULL)
return 1;
else
return 0;
}
};
char stack::infix_postfix(char postfix[30],char infix[30])
{
char token;
int j=0;
stack s;
for(int i=0;infix[i]!='\0';i++)
{
token=infix[i];
if(isalnum(token)) // CHECK OPERAND IS PRESENT OR NOT IF PRESENT ADD INTO POSTFIX ARRAY
{
postfix[j++]=token;
}
else if(token=='(')
{
s.push(token);
}
else if(token==')')
{
while(s.top1()!='(')
{
postfix[j++]=s.pop();
}
s.pop();
}
else
{
while(prece(token)<=prece(s.top1()) && !s.empty()) //BEFORE INSERTING OPERATOR INTO STACK FIRST CHECK PRECEDENCE OF OPERATOR
{ //AND CHECK STACK IS EMPTY OR WHAT
postfix[j++]=s.pop();
}
s.push(token); //PUSH OPERATOR INTO STACK
}
}
while(s.top1()!=NULL)
{
postfix[j++]=s.pop();
}
postfix[j]='\0';
return *postfix;
}
int prece(char token) //PRECEDENCE FUNCTION TO CHECK PRECEDENCE OF OPERATOR
{
if(token=='*'||token=='/')
return 3;
else if(token=='+'||token=='-')
return 2;
else
return 0;
}
void main()
{
stack s1; //CREATE OBJECT OF CLASS STACK
char infix[30]={0},postfix[30]={0};
cout<<"Enter infix Expression\n";
cin>>infix;
s1.infix_postfix(postfix,infix); // CALL INFIX_POSTFIX FUNCTION USING OBJECT
cout<<postfix;
}
OUTPUT:
//****************OUTPUT*******************
Enter infix Expression
(A+B)
AB+
No comments:
Post a Comment
If you have any problems related to solutions or any concept please let me know.