#include <iostream.h>
#include "stack2.h"

// Private utility function count_items counts the number of
// items on the list.  It does this recursively; if the list is
// NULL the length is 0.  Otherwise, the length is 1 + the length
// of the tail of the list.
int stack::count_items(item *list)
{
  if (list == NULL)
    return 0;
  else
    return (1 + count_items(list->next));
}

// Constructor: initialize the linked list to NULL
stack::stack()
{
  data_list = NULL;
}


// Accessor function to return the number of items on the stack
int stack::size()
{
  return count_items(data_list);
}

// Push a value onto the stack by prepending an element to the
// linked list.
void stack::push(int i)
{
  item *new_top;

  new_top = new item;
  new_top->data = i;
  new_top->next = data_list;
  data_list = new_top;
}

// Pop a value off of the stack by deleting the first element
// on the list and returning its value.
int stack::pop()
{
  item *top;
  int top_value;

  if (data_list == NULL)
    cerr << "stack underflow!\n";
  else {
    top = data_list;
    data_list = data_list->next;
    top_value = top->data;
    delete top;
    return top_value;
  }
}

stack::~stack()
{
  while (data_list != NULL)
    pop();
}

