#ifndef IMPROVEDSTACK_H
#define IMPROVEDSTACK_H
template<typename T>
class Stack
{
public:
Stack();
Stack(const Stack&);
~Stack();
bool empty() const;
T peek() const;
void push(T);
T pop();
int getSize() const;
private:
T* elements;
int size;
int capacity;
void ensureCapacity();
};
template<typename T>
Stack<T>::Stack():size(0),capacity(16)
{
elements = new T[capacity];
}
template<typename T>
Stack<T>::Stack(const Stack& stack)
{
elements = new T[stack.capacity];
capacity = stack.capacity;
size = stack.size;
for (int i = 0; i < size;i++)
{
elements[i] = stack.elements[i];
}
}
template<typename T>
Stack<T>::~Stack()
{
delete[] elements;
}
template<typename T>
bool Stack<T>::empty() const
{
return size == 0;
}
template<typename T>
T Stack<T>::peek() const
{
return elements[size - 1];
}
template<typename T>
void Stack<T>::push(T value)
{
ensureCapacity();
elements[size++] = value;
}
template<typename T>
T Stack<T>::pop()
{
return elements[--size];
}
template<typename T>
int Stack<T>:: getSize() const
{
return size;
}
template<typename T>
void Stack<T>:: ensureCapacity()
{
if(size>=capacity)
{
T *old = elements;
elements = new T[2 * size];
capacity = 2 * size;
for (int i = 0; i < size;i++)
{
elements[i] = old[i];
}
delete[] old;
}
}
#endif
#include<iostream>
#include<vector>
#include<string>
#include<cctype>
#include "ImprovedStack.h"
using namespace std;
void processOperator(Stack<char>& operatorStack,Stack<int>& operandStack)
{
int a = operandStack.pop();
int b = operandStack.pop();
char c = operatorStack.pop();
if(c=='+')
operandStack.push(b + a) ;
if(c=='-')
operandStack.push(b - a);
if(c=='*')
operandStack.push(b * a);
if(c=='/')
operandStack.push(b / a);
}
int main()
{
string expression;
cout << "Enter an expression, motherfucker";
getline(cin, expression);
Stack<char> operatorStack;
Stack<int> operandStack;
for (unsigned i = 0; i < expression.length();i++)
{
if(isdigit(expression[i]))
{
operandStack.push(expression[i]-'0');
}
else
{
if(expression[i]=='+'||expression[i]=='-')
{
while(!operandStack.empty()&&(operatorStack.peek()!='(')&&(operatorStack.peek()!=')'))
{
processOperator(operatorStack,operandStack);
}
operatorStack.push(expression[i]);
}
if(expression[i]=='*'||expression[i]=='/')
{
while(!operandStack.empty()&&(!operatorStack.empty())&&(operatorStack.peek()=='/'||operatorStack.peek()=='*'))
{
processOperator(operatorStack,operandStack);
}
operatorStack.push(expression[i]);
}
if(expression[i]=='(')
{
operatorStack.push(expression[i]);
}
if(expression[i]==')')
{
while(operatorStack.peek()!='(')
{
processOperator(operatorStack, operandStack);
}
operatorStack.pop();
}
}
}
while(!operatorStack.empty())
{
processOperator(operatorStack, operandStack);
}
cout << expression << "=" << operandStack.pop() << endl;
}