Sunday, October 2, 2011

Data Structure C program Prefix Conversion Dev c++

 #include <stdio.h>  
#include <conio.h>
#define MAX 20
struct stack{
int top;
char str[MAX];
}s;//stack
char ex[MAX];//expression
char string[MAX];//string
int main(){
s.top=-1;
void push(char);
char pop();
int isoperand(char);
int getpriority(char);
printf("Enter Expression:");
scanf("%s",ex);
int i=strlen(ex)-1,j=-1,p1,p2;
while(i>=0)
{
if(isoperand(ex[i]))
{
printf("op\n");
string[++j]=ex[i];
}
else if(ex[i]==')')
{
push(')');
printf(")\n");
}
else if(ex[i]=='(')
{
printf("(\n");
while(s.str[s.top]!=')')
{
string[++j]=pop();
}
pop();
}else
{
p1=getpriority(ex[i]);
p2=getpriority(s.str[s.top]);
printf("%d<%d %d\n",p1,p2,p1<p2);
while(p1<p2 && s.top!=-1)
{
string[++j]=pop();
p2=getpriority(s.str[s.top]);
}
push(ex[i]);
}
i--;
}
while(s.top>-1)
string[++j]=pop();
printf("%s",strrev(string));
getch();
}
void push(char x)
{
if(s.top==MAX-1)
printf("Stack is full\nStack overflow\n");
else
{
s.top++;
s.str[s.top]=x;
printf("push %c\n",x);
getch();
}
}
char pop()
{
if(s.top==-1)
{
printf("Stack is emplty\nSTACK UNDERFLOW\n");
getch();
}
else
{
s.top--;
printf("pop %c\n",s.str[s.top+1]);
getch();
return s.str[s.top+1];
}
}
int isoperand(char x)
{
x=tolower(x);
if(x>='a' && x<='z')
return 1;
else
return 0;
}
int getpriority(char x){
if(x=='^')
return 3;
else if(x=='*' || x=='/')
return 2;
else if(x=='+' || x=='-')
return 1;
else
return 0;
}

No comments:

Post a Comment