•

Check out our Community Blogs

Register and join over 40,000 other developers!

### Recent Blog Entries

• phi

I love this community !

• JackJames

hi i am jack i am seo expert jack james would love you to read new post

# Calculate an expression using stack

2 replies to this topic

### #1 bexita

bexita

CC Newcomer

• Just Joined
• 15 posts

Posted 27 November 2011 - 08:45 AM

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.

My code is not working , can someone enlighten me ? Thanks a lot

#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;

};

};

Stack::Stack()
{
}
Stack::~Stack()
{
//Let the compiler to do it
}
void Stack::push (int item)
{
NodePtr pNew= new Node;
pNew -> data = item;
}

int Stack::pop()
{
int item = NULL;
try
{
throw exception ();

item = temp ->data;

delete temp;
}
catch (exception e)
{
cout << " Empty exception caught : Remove head failed "<< endl;
}
return item;
}

bool Stack::isEmpty () const
{
}

int Stack::top ()
{
if (!isEmpty())
}

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;

case '-' :  result =k1 - k2;

default : cout<<"\nInvalid operator. Program exit.";

// push back to stack
s.push(result);
}

}

p++; // Go to next element

}

result= s.pop();

return result;
}

• 0

### #2 AKMafia001

AKMafia001

• 118 posts

Posted 27 November 2011 - 09:37 AM

Why you didn't use break;?
case '+' : 	result =k1 + k2;

case '-' :  result =k1 - k2;

This will execute all the cases after the matching case.
• 0
I think i'm able to write a code for printing "Hello, World!". Proud of that!

### #3 bexita

bexita

CC Newcomer

• Just Joined
• 15 posts

Posted 27 November 2011 - 05:07 PM

I changed but the result is still wrong .
• 0

### Also tagged with one or more of these keywords: linked list, stack

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download