Created
October 4, 2020 02:27
-
-
Save TokisakiKurumi2001/045db1edb187d3a1cd0684ef8c368282 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <string.h> | |
| #include <sstream> | |
| using namespace std; | |
| template <class T> | |
| class AStack { | |
| private: | |
| T * arr; | |
| int size; | |
| int maxSize; | |
| public: | |
| AStack(int size) { | |
| this->maxSize = size; | |
| this->size = 0; | |
| arr = new T[size]; | |
| } | |
| ~AStack() { | |
| delete[] arr; | |
| } | |
| void push(const T & element) { | |
| if (size < maxSize) { | |
| arr[size] = element; | |
| this->size += 1; | |
| } | |
| else { | |
| throw("Stack is full\n"); | |
| } | |
| } | |
| T & pop() { | |
| if (this->size == 0) { | |
| throw("Stack is empty"); | |
| } | |
| else { | |
| static T returnData; | |
| returnData = arr[size - 1]; | |
| this->size -= 1; | |
| return returnData; | |
| } | |
| } | |
| bool isFull() { | |
| return this->size == maxSize; | |
| } | |
| bool isEmpty() { | |
| return this->size == 0; | |
| } | |
| void printStack() { | |
| cout << "================\nStack:\n"; | |
| int i = 0; | |
| for (i = this->size - 1; i >= 0; i--) { | |
| cout << arr[i] << endl; | |
| } | |
| } | |
| void clear() { | |
| delete[] arr; | |
| arr = new T[maxSize]; | |
| } | |
| }; | |
| int add(int a, int b) { | |
| return a + b; | |
| } | |
| int sub(int a, int b) { | |
| return a - b; | |
| } | |
| int multiply(int a, int b) { | |
| return a * b; | |
| } | |
| int divide(int a, int b) { | |
| return b / a; | |
| } | |
| int main(int argc, char const * argv[]) | |
| { | |
| AStack<int> * stack = new AStack<int>(10); | |
| string command = "7 4 -3 * 1 5 + / *"; | |
| stringstream ss(command); | |
| string str; | |
| int (*operation)(int, int); | |
| while (getline(ss, str, ' ')) { | |
| if (str == "+" || str == "-" || str == "*" || str == "/") { | |
| if (str == "+") { | |
| operation = &add; | |
| } | |
| else if (str == "-") { | |
| operation = ⊂ | |
| } | |
| else if (str == "*") { | |
| operation = &multiply; | |
| } | |
| else { | |
| operation = ÷ | |
| } | |
| int num_1 = stack->pop(); | |
| int num_2 = stack->pop(); | |
| int res = (*operation)(num_1, num_2); | |
| stack->push(res); | |
| } | |
| else { | |
| stack->push(stoi(str)); | |
| } | |
| } | |
| cout << "Result: " << (stack->pop()) << endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment