Untitled
unknown
plain_text
3 years ago
4.1 kB
14
Indexable
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class slList {
double data;
slList *prev;
slList(double info) {
data = info;
prev = null;
}
};
class Stack {
slList *top; // pointing to top element
Stack() {
top = null;
}
void push(double info) {
slList *temp = new slList(info);
// temp is a pointer object of class slList
// class_name object_name = new class_constructor;
// temp->data = info, temp->prev = null
temp->prev = top;
top = temp;
}
void pop() {
// sanitary check
if (isEmpty()) {
return;
}
slList *temp = top;
top = top->prev;
free(temp);
}
double topElement() {
if(top == null)
return -1;
return top->data;
}
bool isEmpty() {
// true if stack is empty else false
if(top == null)
return true;
return false;
}
};
bool isOperator(string word) {
if (word == "+" || word == "-" || word == "*" || word == "/")
return true;
return false;
}
bool isEqualSign(string word) {
if(word == "=")
return true;
return false;
}
// This function checks if word is an integer or a double value
bool isOperand(string word) {
// 2.3 2 4 5
int n = word.size(), i, ctr = 0;
for(i=0;i<n;i++){
if(word[i] < '0' && word[i] > '9')
return false;
if(word[i] == '.')
ctr++; // ctr = ctr + 1
}
if(ctr == 0 || ctr == 1)
return true;
return false;
}
int main() {
// infinite loop - we dont know how many inputs to take
while(1){
string s;
cin>>s;
if(s == "0")
break;
stringstream(s);
Stack stack;
cout << s;
while(s >> word) {
// step 1: find if the word is operator or operand
// step 2: if operand, then push word in stack
// step 3: if operator (+ - * /), take first 2 elements of stack, calculate value, pop the 2 elements from stack,
// push the new value into the stack
// step 4: if word == "=", then ans = top element of stack
// step 5: print the output
if (isOperator(word)) {
double first, second;
if (isEmpty()){
cout << "ERROR : Too many operators" << endl;
break;
}
second = stack.top();
stack.pop();
if (isEmpty()){
cout << "ERROR : Too many operators" << endl;
break;
}
first = stack.top();
stack.pop();
double value;
if (word == "+") {
value = first + second;
} else if ( word == "-") {
value = first - second;
} else if ( word == "*") {
value = first * second;
} else {
if (second == "0") {
cout << "ERROR : Division by zero" << endl;
break;
}
value = first / second;
}
stack.push(value);
}
else if (isOperand(word)) {
stack.push(stod(word)); // convert string to double and then push into stack
}
else if (isEqualSign(word)) {
// if stack size is 1
double ans = stack.top();
stack.pop();
if (!isEmpty()) {
cout << "ERROR : Too many operands" << endl;
break;
}
cout << ans << endl;
}
else {
// 2.3.4 5.5 +
cout << "ERROR : Wrong input" <<endl;
}
}
}
return 0;
}Editor is loading...