In: Computer Science
C++ Data Structure
Write a program to change following infix expressions to postfix expressions using a stack
a) D-B+C
b) C*D+A*B
c) (A*B)*C+D*F-C
d) (A-4*(B-C)-D/E)*F
Code:
#include <iostream>
using namespace std;
#include <string.h>
void push(char c);
int pri(char s);
char pop();
int n=20;
int stack[20];
int top=-1;
int main()
{
int i,j=0;
char infix[20],l;
char postfix[20];
gets(infix);
for(i=0;infix[i]!='\0';i++)
{
if(infix[i]=='(')
{
push(infix[i]);
}
else if(infix[i]==')')
{
while(top!=-1 && stack[top]!='(')
{
postfix[j]=pop();
j++;
}
if(stack[top]=='(')
{
pop();
}
}
else if(isdigit(infix[i]) || isalpha(infix[i]))
{
postfix[j]=infix[i];
j++;
}
else if(infix[i]=='+' || infix[i]=='-' || infix[i]=='*' ||
infix[i]=='/' || infix[i]=='%')
{
while(top!=-1 && infix[i]!='(' &&
(pri(stack[top])>pri(infix[i])))
{
postfix[j]=pop();
j++;
}
push(infix[i]);
}
else
{
}
}
while(top!=-1 && stack[top]!='(')
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';
puts(postfix);
return 0;
}
void push(char c)
{
top++;
stack[top]=c;
}
char pop()
{
char d;
d=stack[top];
top--;
return d;
}
int pri(char s)
{
if(s=='*' || s=='/' || s=='%')
return 1;
else if(s=='+' || s=='-')
return 0;
else
return -1;
}
Ouput:
Indentation: