Hi , i need to calculate an expression with +/- only , it will get result once it see '=' sign using stack linked list (for exp: 200-100=) ,result 100. (multi digit needed)
My code is not working , can someone enlighten me ? Thanks a lot
Code:
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <ctime>
using namespace std;
const int MAX =100;
int getResult(char *);
class Stack
{
public:
Stack();
~Stack();
void push(int);
int pop();
int top ();
bool isEmpty () const;
private:
struct Node;
typedef Node* NodePtr ;
struct Node
{
int data;
NodePtr next;
};
NodePtr head;
};
Stack::Stack()
{
head =NULL;
}
Stack::~Stack()
{
//Let the compiler to do it
}
void Stack::push (int item)
{
NodePtr pNew= new Node;
pNew -> data = item;
pNew -> next = head;
head = pNew;
}
int Stack::pop()
{
int item = NULL;
try
{
if ( head == NULL)
throw exception ();
NodePtr temp = head;
head = head ->next;
item = temp ->data;
delete temp;
}
catch (exception e)
{
cout << " Empty exception caught : Remove head failed "<< endl;
}
return item;
}
bool Stack::isEmpty () const
{
return head == NULL;
}
int Stack::top ()
{
if (!isEmpty())
return head-> data;
}
int main ()
{
char * exp = new char[MAX];
cout <<"Enter an expression" <<endl;
cin.getline(exp,MAX);
int result = getResult (exp);
cout <<result <<endl;
}
int getResult(char *exp)
{
int i =0;
int k,k1,k2;
int result = 0;
char *p;
Stack s;
p = &exp[0];
// Calculate the result if last element is '=' sign
while (*p!='=')
{
/* To remove spaces and tabs*/
while (*p ==' ' || *p =='\t')
{
p++;
}
// If is operand
if (isdigit(*p))
{
s.push(*p);
}
else
{
//If is operator +,-
k1 = s.pop();
k2 = s.pop();
switch (*p)
{
case '+' : result =k1 + k2;
break;
case '-' : result =k1 - k2;
break
default : return result;
// push back to stack
s.push(result);
}
}
p++; // Go to next element
}
result= s.pop();
return result;
}