#include <iostream>
#include <string>
using namespace std;
class StackNode
{
public:
StackNode * topPtr = NULL;
StackNode* next;
string item;
bool push( string newItem) {
// create a new node
StackNode *newPtr = new StackNode;
// set data portion of new node
newPtr->item = newItem;
// insert the new node
newPtr->next = topPtr;
topPtr = newPtr;
return true;
}
bool pop() {
if (topPtr == NULL)
return false;
// stack is not empty; delete top
else{
StackNode *temp = topPtr;
topPtr = topPtr->next;
// return deleted node to system
temp->next = NULL; // safeguard
delete temp;
return true;
}
}
int ope(string op, string val1,string val2)
{
int vaL1 = stoi(val1);
int vaL2 = stoi(val2);
int res = 0;
if( op == "*")
res = vaL1 * vaL2;
if( op == "/")
res = vaL1 / vaL2;
if( op == "-")
res = vaL1 - vaL2;
if( op == "+")
res = vaL1 + vaL2;
return res;
}
int cal(string pre_exp[],int len)
{
int numb = 0;
for(int i = len -1;i>=0;i--)
{
if ( pre_exp[i] == "*" || pre_exp[i] == "/" || pre_exp[i] == "+" || pre_exp[i] == "-")
{
string op1 = topPtr->item;
pop();
string op2 = topPtr->item;
pop();
numb = numb + ope(pre_exp[i],op1,op2);
}
else
{
push( (pre_exp[i]));
}
}
return numb;
}
int main()
{
StackNode nbr;
string eyoo[] = {"+","-","2","3","9"};
cout<< nbr.cal(eyoo,5)<<endl;
return 0;
}
Hello everyone, I am trying find the sum of a prefix expression. My code is here. Weirdly, I don't get any output. The method cal does not return the number, probably the program gets stucks in the for loop of the method calc. Can someone help me please? Pop and push methods work, I tested them with a display method. The problem must be in the usage of stoi or in the calc method as I said.
string op1 = topPtr->item;
pop();
string op2 = topPtr->item;
pop();
you always pop the 2 operands of an operator, that supposes you push the result, but you do not do, at a given time topPtr become null, with your example this is when you do string op2 = topPtr->item;
for me numb = numb + ope(pre_exp[i],op1,op2);
must be replaced by pushing the result of ope(pre_exp[i],op1,op2)
in the stack at the place of the two poped values
so for {"+","-","2","3","9"}
:
-
so pop=2 - pop=3 = -1, and you have to push -1+
so pop=-1 + pop=9 = 8 and you push 8 (without the push -1 before the stack is empty when getting the second operand)However I am surprised you star by the end of the expression, I am not sure that works in all the case an compute well the result, why you do not start by the beginning ?
A final remark : all your method try to be inline (defined in the class), we use inline when a method is small, better to move the definitions out of the class for your methods