1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
|
#include <iostream>
#include <string>
#include <cctype>
int applyOp(char, int, int);
using namespace std;
class Node
{
int val; //variable for operators
char op; //variable for operands
Node* next; //points to next node in list
friend class LinkedStack;
};
class LinkedStack
{
Node* top;
Node* curr;
public:
LinkedStack()
{
top = NULL;
}
void pushVal(const int&);
void pushOp(const char&);
int popVal();
char popOp();
int topOfValStack();
char topOfOpStack();
bool hasPrec(const char&, const char&);
bool isEmpty();
};
void LinkedStack::pushVal(const int& num)
{
Node* t = new Node; //create new node
int a = num - '0'; //convert charater '0' -> 0
t->val = a; //assign operand
t->next = top; //t's next points to top
top = t; //make t the top node
}
void LinkedStack::pushOp(const char& e)
{
Node* t = new Node;
t->op = e;
t->next = top;
top = t;
}
int LinkedStack::popVal()
{
Node* old = top;
top = old->next;
delete old;
return top->val;
}
char LinkedStack::popOp()
{
Node* old = top;
top = old->next;
delete old;
return top->op;
}
int LinkedStack::topOfValStack()
{
return top->val;
}
char LinkedStack::topOfOpStack()
{
return top->op;
}
bool LinkedStack::hasPrec(const char& e, const char& f)
{
if((e == '*' || e == '/'))
{
return false;
}
else
{
return true;
}
}
bool LinkedStack::isEmpty()
{
return top == NULL;
}
int applyOp(char op, int x, int y)
{
switch(op)
{
case '*': return y * x;
break;
case '/':
if(x == 0)
{
cout << "Cannot divide by 0\n";
return 0;
}
else
{
return y / x;
}
break;
case '+': return y + x;
break;
case '-': return y - x;
break;
default:
cout << "Expression entered incorrectly\n";
return 0;
}
}
int main()
{
LinkedStack valStack;
LinkedStack opStack;
string exp;
cout << "Enter an arithmetic expression including the following operators.(+, -, *, /)\n";
cin >> exp;
for(int i = 0; i < exp.size(); i++)
{
if(isdigit(exp[i]))
{
valStack.pushVal(exp[i]);
}
else if(exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/')
{
while(!opStack.isEmpty() && opStack.hasPrec(exp[i],opStack.topOfOpStack()))
{
valStack.pushVal(applyOp(opStack.popOp(), valStack.popVal(), valStack.popVal()));
}
opStack.pushOp(exp[i]);
}
}
//After entire expression is parsed, apply remaining operations to remaining operands
while(!opStack.isEmpty())
{
valStack.pushVal(applyOp(opStack.popOp(), valStack.popVal(), valStack.popVal()));
}
//Print top operand of valStack
cout << valStack.topOfValStack();
return 0;
}
|