Stack Applications
[Link] of an infix expression into a prefix expression
[Link] of an infix expression into a postfix expression
//[Link] a C program to convert an infix expression into its equivalent
prefix expression
/*#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define MAX 50
int top=-1;
char s[MAX];
void push(char x)
{
if(top==MAX-1)
printf("Stack is overflow\n");
else
{
top=top+1;
s[top]=x;
}
}
char pop()
{
char ch;
if(top==-1)
printf("Stack is underflow/empty\n");
else
{
ch=s[top];
top=top-1;
}
return ch;
}
int priority(char x)
{
if(x==')' || x=='(')
return 0;
if(x=='+' || x=='-')
return 1;
if(x=='*' || x=='/' || x=='%')
return 2;
}
void reverse(char str[])
{
char temp;
int i=0,j,len;
len=strlen(str);
j=len-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
}
void main()
{
char infix[50],prefix[50],ch;
int i=0,k=0;
printf("Enter infix expression : ");
scanf("%s",infix);
reverse(infix);
while((ch=infix[i++])!='\0')
{
if(ch==')')
push(ch);
else if(isalnum(ch))
prefix[k++]=ch;
else if(ch=='(')
{
while(top!=-1 && s[top]!=')')
prefix[k++]=pop();
pop();//Discarding right parentheses from stack
}
else
{
while(top!=-1 && priority(s[top]) > priority(ch))
prefix[k++]=pop();
push(ch);
}
}
while(top!=-1)
prefix[k++]=pop();
prefix[k++]='\0';
//Reversing the prefix to get final prefix expression
reverse(prefix);
printf("The prefix expression is : %s\n",prefix);
}
//[Link] a C program to convert an infix expression into its equivalent
postfix expression
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define MAX 50
int top=-1;
char s[MAX];
void push(char x)
{
if(top==MAX-1)
printf("Stack is overflow\n");
else
{
top=top+1;
s[top]=x;
}
}
char pop()
{
char ch;
if(top==-1)
printf("Stack is underflow/empty\n");
else
{
ch=s[top];
top=top-1;
}
return ch;
}
int priority(char x)
{
if(x==')' || x=='(')
return 0;
if(x=='+' || x=='-')
return 1;
if(x=='*' || x=='/' || x=='%')
return 2;
}
void reverse(char str[])
{
char temp;
int i=0,j,len;
len=strlen(str);
j=len-1;
while(i<j)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
i++;
j--;
}
}
void main()
{
char infix[50],postfix[50],ch;
int i=0,k=0;
printf("Enter infix expression : ");
scanf("%s",infix);
while((ch=infix[i++])!='\0')
{
if(ch=='(')
push(ch);
else if(isalnum(ch))
postfix[k++]=ch;
else if(ch==')')
{
while(top!=-1 && s[top]!='(')
postfix[k++]=pop();
pop();//Discarding left parentheses from stack
}
else
{
while(top!=-1 && priority(s[top]) >= priority(ch))
postfix[k++]=pop();
push(ch);
}
}
while(top!=-1)
postfix[k++]=pop();
postfix[k++]='\0';
printf("The postfix expression is : %s\n",postfix);
}