-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.h
More file actions
72 lines (63 loc) · 1.87 KB
/
Stack.h
File metadata and controls
72 lines (63 loc) · 1.87 KB
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
//
// Created by timot on 11/1/2021.
//
#ifndef ASSIGNMENT4_STACK_H
#define ASSIGNMENT4_STACK_H
#include <vector>
#include <string>
class Stack{
private:
std::vector<char*> stackData;
public:
Stack()= default;
//add to stack
void push(char* data){
stackData.push_back(data);
}
//remove and return top of stack
char* pop(){
char* data = stackData.at(stackData.size()-1);
stackData.pop_back();
return data;
}
//return size of stack
int size(){
return stackData.size();
}
//return top of stack but don't remove from stack
char* top(){
return stackData.at(stackData.size()-1);
}
//loop through stack and print contents
void print(){
for(char* i : stackData){
std::cout << i << std::endl;
}
}
//set the capacity of the stack only if it is larger
void setCapacity(size_t capacity){
if(stackData.capacity() < capacity){
stackData.reserve(capacity);
}
}
//solve RPN using this stack
double evaluate(){
//this char should always be an operation character because of notation
char operation = *this->pop();
//check if there is another operation and if so recursive call
double operand1 = (!std::isdigit(*this->top())) ? evaluate() : atof(this->pop());
double operand2 = (!std::isdigit(*this->top())) ? evaluate() : atof(this->pop());
//convert char operation to operations
switch (operation) {
case '+' :
return operand2 + operand1;
case '-':
return operand2 - operand1;
case '*':
return operand2 * operand1;
case '/':
return operand2 / operand1;
}
}
};
#endif //ASSIGNMENT4_STACK_H