// StackType.cpp
// Class is templated; implementation is linked.

#include <cstddef>      //for NULL

//a node of a linked list is a struct with 2 members: the template argument
//type info and a pointer to the same kind of node:
template <class ItemType>
struct NodeType
{
   ItemType info;
   NodeType<ItemType>* next;
};
//**********************************************

template<class ItemType>
StackType<ItemType>::StackType()
{
    topPtr = NULL;
}

template<class ItemType>
void StackType<ItemType>::Pop(ItemType& item)
  //remove from front of linked list
{
    NodeType<ItemType>* tempPtr;
    tempPtr = topPtr;
    //order of the 2 following statements is important:
    item = topPtr ->info;
    topPtr = topPtr->next;
    delete tempPtr;
}

template<class ItemType>
bool StackType<ItemType>::IsFull() const
  //try to allocate, if can't Stack is full
{
    NodeType<ItemType>* ptr;
    ptr = new NodeType<ItemType>;
    if (ptr == NULL)
      return true;
    else {
      delete ptr;    //deallocate
      return false;
    }
}

template <class ItemType>
void StackType<ItemType>::Push(ItemType newItem)
  //prepend to front of linked list
{
    NodeType<ItemType>* ptr;
    ptr = new NodeType<ItemType>;    //get a new node
    ptr->info = newItem;             //put data ItemType into it
    ptr->next = topPtr;              //have it point to first node in list
    topPtr = ptr;                    //topPtr point to it.  it's first node in list
}

template <class ItemType>
void StackType<ItemType>::MakeEmpty() 
{
    NodeType<ItemType>* tempPtr;

    cout << "hi from MakeEmpty" << endl;

    //traverse the list, deleting nodes.
    while (topPtr != NULL) {
      tempPtr = topPtr;
      topPtr = topPtr->next;
      delete tempPtr;
    }
}

template <class ItemType>
StackType<ItemType>::~StackType()
{
  cout << "hi from dtor" << endl;
  //MakeEmpty does what is needed, so use it.  Avoid duplicating code.
  MakeEmpty();
}

template <class ItemType>
bool StackType<ItemType>::IsEmpty() const
{
    return (topPtr == NULL);
}

