Netaji Subhas Institute of Technology
2011
Data Structures Lab
C++ Programmes
Prepared By:
Vinayak Garg
326/CO/09
COE - II
Infix to Postfix and Evaluation
Code
#include<iostream>
#include<ctype.h>
#include<math.h>
#define STACK_SIZE 20
#define STRING_SIZE 40
using namespace std;
class charstack{
char list[STACK_SIZE];
int top;
public:
charstack() {
top=-1;
}
void push(char);
char pop();
char peek();
};
void charstack::push(char x)
{
if(top==STACK_SIZE-1)
cout<<"Overflow\n";
else {
top++;
list[top]=x;
}
}
char charstack::pop()
{
if(top==-1)
return 0;
else {
char x=list[top];
top--;
return x;
}
}
char charstack::peek()
{
if(top==-1) return 0;
else return list[top];
}
class infixtopostfix
{
char infix[STRING_SIZE];
char postfix[STRING_SIZE];
charstack operators;
int precedence(char);
public:
void read();
void process();
void print() {
cout<<"The postfix expression : "<<postfix<<endl;
}
char * getPostfix() {
return postfix;
}
};
void infixtopostfix::read()
{
cout<<"Enter the infix expression : ";
cin>>infix;
}
int infixtopostfix::precedence(char a)
{
switch(a) {
case '^': return 3;
case '*':
case '/': return 2;
case '+':
case '-': return 1;
default: return 0;
}
}
void infixtopostfix::process()
{
int i,j;
char temp;
for(i=0,j=0; infix[i]!='\0'; i++) {
if(isalpha(infix[i])) {
postfix[j]=infix[i];
j++;
} else if(infix[i]=='(') {
[Link]('(');
} else if(infix[i]==')') {
temp=[Link]();
while(temp!='(') {
postfix[j]=temp;
j++;
temp=[Link]();
}
} else {
temp=[Link]();
while(precedence(infix[i])<=precedence(temp)) {
[Link]();
postfix[j]=temp;
j++;
temp=[Link]();
}
[Link](infix[i]);
}
}
temp=[Link]();
while(temp!=0) {
postfix[j]=temp;
j++;
temp=[Link]();
}
postfix[j]='\0';
}
class intstack
{
int list[STACK_SIZE];
int top;
public:
intstack() { top=-1; }
void push(int);
int pop();
};
void intstack::push(int x)
{
if(top==STACK_SIZE-1)
cout<<"Overflow\n";
else {
top++;
list[top]=x;
}
}
int intstack::pop()
{
if(top==-1) return 0;
else {
int x=list[top];
top--;
return x;
}
}
class postfixevaluation
{
intstack operand;
int value;
public:
postfixevaluation(char *);
};
postfixevaluation::postfixevaluation(char *s)
{
for(int i=0,j=0;s[i]!='\0';i++)
if(isalpha(s[i])) {
cout<<"Enter value for "<<s[i]<<" : ";
cin>>value;
[Link](value);
} else {
int op1,op2;
op1=[Link]();
op2=[Link]();
switch(s[i]) {
case '+':[Link](op2+op1);break;
case '-':[Link](op2-op1);break;
case '*':[Link](op2*op1);break;
case '/':[Link](op2/op1);break;
case '^':[Link](pow(op2,op1));break;
}
}
cout<<"The value of expression = "<<[Link]();
}
int main()
{
infixtopostfix myObject;
[Link]();
[Link]();
[Link]();
postfixevaluation myObject2([Link]());
return 0;
}
Output
Enter the infix expression : a+(b*c-d/e)*(f+g)^h
The postfix expression : abc*de/-fg+h^*+
Enter value for a : 7
Enter value for b : 6
Enter value for c : 3
Enter value for d : 8
Enter value for e : 4
Enter value for f : 1
Enter value for g : 5
Enter value for h : 2
The value of expression = 583