#include<iostream.h>
#include<math.h>
#include<conio.h>
#define
maxS 10
struct stack
{
int isi[maxS];
int top;
};
void INITS(stack &s);
void push(stack &s, int elemen);
void pop(stack &s,int &data);
void pref(char y, int &x);
void cetak(stack s);
main()
{
char prefiks[20];
stack s;
char y;
int i,n, data1, data2,x;
INITS(s);
cout<<"****Evaluasi Notasi Prefiks dan Notasi Postfiks****\n\n";
cout<<"Masukkan bilangan :
";cin>>prefiks;
n=strlen(prefiks);
for(i=n-1;i>=0;i--)
{
y = prefiks[i];
cout<<"\n X =
"<<y;
if(y=='^' || y=='*'||y=='/' ||
y=='+'||y=='-')
{
pop(s, data1);
pop(s, data2);
switch (y)
{
case '^' : x = pow(data1,data2);
break;
case '*' : x = data1*data2;
break;
case '/' : x = data1/data2;
break;
case '+' : x = data1+data2;
break;
case '-' : x = data1 - data2;
}
push(s,x);
}
else
{
pref(y,x);
push(s,x);
cetak(s);
cout<<endl;
}
}
cetak(s);
pop(s,data1);
cout<<"\n\nHasil Ekspresi =
"<<data1;
getch();
}
void INITS(stack &s)
{
s.top=0;
}
void
push(stack &s, int elemen)
{
if(s.top < maxS)
{
s.top++;
s.isi[s.top] = elemen;
}
else
cout<<" stack Penuh
......";
}
void pop(stack &s,int &data)
{
if(s.top != 0)
{
data=s.isi[s.top];
s.top--;
}
else
cout<<" Stack Kosong ....";
}
void pref(char y, int &x)
{
if(y== '1')
x=1;
else if(y== '2')
x=2;
else if(y== '3')
x=3;
else if(y== '4')
x=4;
else if(y== '5')
x=5;
else if(y== '6')
x=6;
else if(y== '7')
x=7;
else if(y== '8')
x=8;
else if(y== '9')
x=9;
}
void cetak(stack s)
{
int i;
cout<<endl<<"Isi stack :
";
if(s.top != 0)
{
for(i=1;i<=s.top;i++)
{
cout<<s.isi[i];
}
}
else
cout<<" Stack Kosong
......";
}
Tidak ada komentar:
Posting Komentar