الجمعة، 23 نوفمبر 2012
الأحد، 18 نوفمبر 2012
Postfix to Prefix Expression
// into Prefix Expression
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
struct oprtor
{
int pstion[30]; // to hold the position where the operator should be added in
// prefix conversion
int top ;
char array [30];
} o; // to store the operators during the process
struct oprtor temp; // to temporarily hold operators before pushing them into o
void push ( struct oprtor *o , char el , int position ) // used to push operators into ( o ) or ( temp )
{
if ( o->top == 29 )
{
cout << "Stack is full " << endl;
getch();
exit ( 1 );
}
o->array [ ++o->top ] = el ;
o->pstion[ o->top ] = position ;
}
char pop ( struct oprtor *o ) // to pop operators from the oprtor or temp
{
if ( o->top == -1 )
{
cout << " The stack is empty " << endl ;
getch();
exit ( 1 );
}
return ( o->array [ o->top --] ) ;
}
int isoprnd ( char a )
{
if ( (a >= 'A' && a <= 'Z' ) ||(a >= 'a' && a <= 'z' ) )
return 1;
else
return 0;
}
int isoprtor ( char a )
{
switch ( a )
{
case '+' :
case '-' :
case '*' :
case '/' :
case '$' :
return 1 ;
default :
return 0 ;
}
}
int main ()
{
char postfix[30] , prefix[30];
int post =0 , pre = -1 ;
int position = 2 , tempint ;
char tempop;
int i = 0;
o.top = -1;
temp.top = -1 ;
cout << "Please enter an expression using Postfix form : \n\n";
cin >> postfix ;
while (postfix[post] != '\0')
{
if ( ! isoprnd(postfix[post]) && ! isoprtor (postfix[post]))
{
cout<< "\nthe expression has improper characters ";
getch();
exit(1);
}
if (isoprnd(postfix[post]))
i ++;
if (isoprtor(postfix[post]))
i --;
post ++;
}
post -- ;
if ( i != 1 ) // to check that each operator has 2 operands
{
cout << " The expression is invalid \n\n\n" ;
getch();
exit (1);
}
while(post != -1)
{
if(isoprtor( postfix[post]))
{
position = 2;
for(i = post-1; position !=0 ; i --)
{
if(isoprnd(postfix[i]))
position --;
if(isoprtor(postfix[i]))
position ++;
}
if ( i < -1 )
{
cout<<"\nThe order of operators is incorrect";
getch();
exit(1);
}
position = i+1;
if (position < post-2) // operator's operands are more than 2 characters
push(&temp , postfix[post] , position);
else // operator's operands are just 2 characters
{
push(&o,postfix[post],position
while(temp.top != -1 && temp.pstion[temp.top] == position)
{
tempint = temp.pstion[temp.top];
tempop = pop(&temp);
push(&o, tempop, tempint);
}
}
}
post -- ;
}
while(temp.top != -1)
{
tempint = temp.pstion[temp.top];
tempop = pop(&temp);
push(&o,tempop,tempint);
}
// Now start reading from the beginning of the postfix string
post = 0;
while(postfix[post] !='\0')
{
if (isoprnd(postfix[post]))
{
while( o.top != -1 && o.pstion[o.top] == post)
{
pre ++;
prefix[pre] = pop(&o);
}
pre ++;
prefix[pre] = postfix[post];
}
post ++;
}
cout<<"\n\nthe string in the prefix form is :\n\n";
for (i = 0; i <= pre; i ++)
cout<<prefix[i];
getch();
return 0 ;
}
السبت، 17 نوفمبر 2012
الاشتراك في:
الرسائل (Atom)