Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <string>
- #include <iostream>
- #include "Stack.h"
- #include <stdlib.h>
- using namespace std;
- void Stacker()
- {
- Stack s;
- s.push(1);
- s.push(2);
- s.push(3);
- s.push(4);
- s.push(5);
- s.push(6);
- s.push(7);
- cout << s.getTop()<<endl ;
- s.displayInOrder();
- s.displayInOrderOfInsertion();
- s.pop();
- s.displayInOrderOfInsertion();
- cout << endl << endl << endl << endl;
- }
- int Precedence(char c)
- {
- if (c == '^')
- {
- return 3;
- }
- else if (c == '*' || c == '/')
- {
- return 2;
- }
- else if(c =='+'||c=='-')
- {
- return 1;
- }
- else
- {
- return 0;
- }
- }
- string Infix()
- {
- string infix; //Input string
- string output = ""; //Output string
- Stack operators; //Store stack of operators
- string operate = "+-*/^";
- cout << "Please enter your infix expression : ";
- getline(cin, infix);
- for (int i = 0; i < infix.length(); i++)
- {
- if (infix[i] == ' ')
- {
- }
- else
- {
- char c = infix[i];
- if (isalpha(c) || isdigit(c))
- {
- output += c;
- }
- else
- {
- if (c == ')')
- {
- //do something
- while (operators.getTop() != '(')// while top of stack is not '('
- {
- output += operators.getTop();
- operators.pop();
- }
- operators.pop();
- }
- else if (operators.isEmpty())
- {
- operators.push(c);
- }
- else
- {
- if (c == '(')
- {
- operators.push(c);
- }
- else
- {
- if (Precedence(operators.getTop()) >= Precedence(c))// If current stack top higher or equal precedence than c
- {
- while (Precedence(operators.getTop()) >= Precedence(c))
- {
- output += operators.getTop();
- operators.pop();
- }
- operators.push(c);
- }
- else
- {
- operators.push(c);
- }
- }
- }
- }
- cout << c << " read, Output string = (" << output << ") Stack operators = ("; operators.displayInOrder(); cout << ")";
- cout << endl;
- }
- }
- cout << "Leftover stack = "; operators.displayInOrder(); cout << endl;
- while (!operators.isEmpty())
- {
- output.append(1, operators.getTop());
- operators.pop();
- }
- cout << output << endl;
- return output;
- }
- int Cal(char c, int a, int b)
- {
- if (c == '/')
- {
- return a / b;
- }
- else if (c == '+')
- {
- return a + b;
- }
- else if (c == '*')
- {
- return a * b;
- }
- else if (c == '-')
- {
- return a - b;
- }
- else
- {
- return a ^ b;
- }
- }
- void Evaluate()
- {
- string infix = Infix();
- Stack s;// stack for numbers
- int first, second, result, num;
- for (int i = 0; i < infix.length(); i++)
- {
- char c = infix[i];
- if (isalnum(c))
- {
- //num is stored as int now;
- num = c - '0';
- s.push(num);
- }
- else
- {
- //imagine 21-
- first = s.getTop(); //1
- s.pop();
- second = s.getTop();//2
- s.pop();
- result = Cal(c, second, first);
- s.push(result);
- }
- }
- //COUT << static_cast <CHAR>(GETTOP())
- cout << "Result = " << static_cast <int>(s.getTop());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement