Arithmetic using stacks
could have used vector
but would have caused an efficiency cnocern
Arithmetic in C++

4+11*8

Should be 92.  But can be viewed as ambigious - must paranthesize it. 

Let's make a function that does this: 
47 + 8 x = (4+7)x8 = 88
478 x+ = (7x8)+4 = 60

Evaluate function using stacks

//for each operator, takes two previous numbers and does something to it

bool evaluate(Stack& memory, string expr) {

 for(int i=0; i    if(isOperator(expr[i])) {
      if(memory.size()<2) return false;
      int second = memory.pop();
      int first = memory.pop();
      memory.push(combine(first, expr[i], second));
   } else {
      memory.push(expr[i] - 'o');
   }
 }
 return memory.size()==1;
}

Combine function

int combine(int one, char op, int two) {
  switch(op) {
    case '+': return one+two;
    case '-': return one-two;
    case '*': return one*two;
    case '/': return one/two;
    case '%': return one%two;
  }

}

why stacks?
proves how reducing interface can actually have benefits
Queues
why queues?
can be used in circumstances where you go in circles for something, and the size of the circle is dynamically changing
Queue survivor game example

int lastKilled=0;
int nextToLastKilled=0;
determineSurvivors(42,7,lastKilled,nextToLastKilled);

determine survivors using stacks

void ds(int numPeople, int numToSpare, int& lastKilled, int& nextToLastKilled) {
   Queue<int> circle;
   for(int n=1; n<=numPeople; n++)  circle.enqueue(n);
   while(!circle.isEmpty())  {
      for(int i=0; i<numToSpare; i++) {
         circle.enqueue(circle.dequeue());
      }
      nextToLastKilled = lastKilled;
      lastKilled = circle.dequeue();
}

   Login to remove ads X
Feedback | How-To