/* intstack.cpp - variation on Prof. LaFollette's code
 */

#include <iostream>
using namespace std;
#include "intstack.h"

inline void checkStackAlloc(int *p)
{
	if (p == 0) {
	   cout << "Memory allocation failed while creating stack." << endl;
	   exit(1);
	}
}

IntStack::IntStack(int maxSize = 100): length(maxSize), sp(0)
{
  body = new int[length];
  checkStackAlloc(body);
}

IntStack::IntStack(const IntStack &rhs) //copy constructor
{
  length = rhs.length;
  sp = rhs.sp;
  body = new int[length];
  checkStackAlloc(body);
  for (int i = 0; i < sp; i++)
      body[i] = rhs.body[i];
}

IntStack::~IntStack() //destructor
{
  delete [] body;
}

//Deep copy assignment operator
IntStack& IntStack::operator=(const IntStack& rhs) 
{
  if (this != &rhs) //do nothing if we are copying something to itself
  {
    sp = rhs.sp;
    length = rhs.length;
    delete [] body;
    body = new int[length];
    checkStackAlloc(body);
    for (int i = 0; i < sp; i++)
        body[i] = rhs.body[i];
  }
  return *this;
}

/*
//Shallow copy assignment operator
IntStack& IntStack::operator=(const IntStack& rhs) //assignment operator
{
  if (this != &rhs) //do nothing if we are copying something to itself
  {
    delete [] body;
    body = rhs.body;
    sp = rhs.sp;
    length = rhs.length;
  }
  return *this;
}
*/

bool IntStack::isempty() const
{
  return (sp <= 0);
}

bool IntStack::isfull() const
{
  return (sp >= length);
}

void IntStack::push(int value)
{
  if ( isfull() )
  {
    cout << "Stack Overflow" << endl;
    exit(1);
  }
  body[sp++] = value;
}

int IntStack::pop() 
{
  if ( isempty() )
  {
    cout << "Stack Underflow" << endl;
    exit(1);
  }
  sp--;
  return (body[sp]);
}

int IntStack::peek() const
{
  if ( isempty() )
  {
    cout << "Stack Underflow" << endl;
    exit (1);
  }
  return (body[sp-1]);
}









