Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define MAX 10
- #include "iostream"
- #include "cmath"
- using namespace std;
- class myStack {
- int top;
- int store[MAX];
- public:
- void stack_initialize();
- void push(int);
- void pop();
- int get_top();
- void show();
- };
- void myStack::stack_initialize() {
- top = -1;
- }
- void myStack::push(int X) {
- if (top >= MAX - 1) {
- cout << "\nOverFlow Error : Your stack is full.\n";
- } else {
- top++;
- store[top] = X;
- cout << "\nPush done..!" << endl;
- }
- }
- void myStack::pop() {
- if (top < 0) {
- cout << "\nUnderFlow Error : Your stack is empty.\n";
- } else {
- top--;
- cout << "\nPop done..!" << endl;
- }
- }
- int myStack::get_top() {
- return store[top];
- }
- void myStack::show() {
- for (int i = top; i >= 0; i--) {
- cout << "|" << store[i] << "|" << endl;
- }
- }
- int main() {
- string postfix; myStack ss;
- cout << "Give your Arithmetic Expression in Postfix notation (Put space between different operands and operators)." << endl;
- cout << "\nLike : 2 3 * -21 - 3 / 5 33 * + , which evaluates 174." << endl;
- cout << "\nPostfix Expression : "; getline(cin, postfix); ss.stack_initialize();
- for (int i = 0; postfix[i] != '\0'; i++) {
- if (int(postfix[i]) >= 48 && int(postfix[i]) <= 57) {
- int num = int(postfix[i]) - 48;
- if (postfix[i + 1] == ' ') {
- ss.push(num);
- } else {
- i++;
- while (int(postfix[i]) >= 48 && int(postfix[i]) <= 57) {
- num *= 10;
- num += (int(postfix[i]) - 48);
- i++;
- }
- i--;
- ss.push(num);
- }
- }
- else if (postfix[i] == ' ') continue;
- else if (postfix[i] == '-') {
- if (postfix[i + 1] == ' ' || postfix[i + 1] == '\0') {
- int y = ss.get_top(); ss.pop();
- int x = ss.get_top(); ss.pop();
- ss.push(x - y);
- } else {
- i++;
- int num = int(postfix[i++]) - 48;
- while (int(postfix[i]) >= 48 && int(postfix[i]) <= 57) {
- num *= 10;
- num += (int(postfix[i]) - 48);
- i++;
- }
- i--;
- ss.push( -1 * num);
- }
- }
- else {
- int y = ss.get_top(); ss.pop();
- int x = ss.get_top(); ss.pop();
- if (postfix[i] == '+' ) {
- ss.push(x + y);
- }
- else if (postfix[i] == '*') {
- ss.push(x * y);
- }
- else if (postfix[i] == '/') {
- ss.push(x / y);
- }
- else if (postfix[i] == '^') {
- ss.push(pow(x, y));
- }
- else if (postfix[i] == '%') {
- ss.push(x % y);
- }
- }
- }
- cout << "\n\nEvaluation done, Ans: " << ss.get_top() << "." << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment