Evaluate
RPN Expression & Detect Whether it is a Well formed Expression or Not……
ALGORITHM
C++
CODE
#include "stdafx.h"
#include "iostream"
using namespace std;
///////////////////////////////// DEFINITION OF STACK ///////////////////////////////////
class stack
{
int top, opers[100];
public:
stack( ) : top(-1) { }
void push(int a)
{ opers[++top]
= a; }
int pop( )
{ return
opers[top--]; }
int peek( )
{ return
top; }
bool isempty( )
{
if(top == -1) return
true;
else return false;
}
};
///////////////////////////////// DECLARATION OF op() ///////////////////////////////////
void op(char*);
/////////////////////////////////////////////////////////////////////////////////////////
void main()
{
char exp[100];
cout<<"enter
an RPN expression: "; cin.getline(exp,100);
op(exp);
}
///////////////////////////////// DEFINITION OF op() ////////////////////////////////////
void op(char* exp)
{
int ans, b, top2[2];
char token; stack
s;
for(int i = 0; i < strlen(exp);
i++)
{
token = exp[
i ];
switch(token)
{
case ' ': break;
case '+': case '-': case
'*': case '/':
for(int
j = 0; j < 2; j++)
{
if(
s.isempty( ) )
{ cout << "Error in RPN
exp..." << endl; exit(1); }
else
top2[j]
= s.pop( );
}
if(token
== '+') ans = top2[1] +top2[0];
if(token
== '-') ans = top2[1] - top2[0];
if(token
== '*') ans = top2[1] * top2[0];
if(token
== '/') ans = top2[1] / top2[0];
s.push(
ans );
break;
default:
b
= token - '0';
s.push(b);
break;
}
if(token !=
' ')
cout
<< "Token = " << token << endl;
}
if(s.peek( ) != 0)
cout << "RPN
expression is NOT Well Formed..." << endl;
else
cout
<< "RPN expression is Well Formed..." << endl;
}
OUTPUT:
0 comments: