/*
  liststack.c
  Implementation of the stack ADT using a linked list structure
  Nadeem Abdul Hamid
  Fall 2006 - Berry College - CSC220
*/

#include <stdlib.h>
#include "stack.h"
#include "../list/node.h"

struct stack
{
  int size;
  LIST top;
};


/* creates a new stack with initial capacity */
STACK createStack() 
{
  STACK s = (STACK) malloc(sizeof(struct stack));
  s->size = 0;
  s->top = NULL;
  return s;
}


/* frees all memory associated with the stack data structure,
   (but does not free any of the actual data items) */
void destroyStack(STACK s) 
{
  destroyList(s->top);
  free(s);
}


/* returns the size of the stack */
int size(STACK s)
{
  return s->size;
}


/* returns whether the stack is empty */
bool isEmpty(STACK s)
{
  return !size(s);
}


/* adds an item to the top of the stack; returns true if successful */
bool push(STACK s, void* item)
{
  NODE *newnode = createNode(item);

  if (!newnode)  /* no memory for new nodes? */
    return false;
  newnode->pnext = s->top;
  s->top = newnode;
  s->size++;
  return true;
}


/* removes and returns the item on top of the stack; returns
   NULL if error */
void* pop(STACK s)
{
  NODE *topnode = s->top;
  void *item;

  if (isEmpty(s))
    return NULL;
  s->top = topnode->pnext;
  s->size--;
  item = topnode->pdata;
  free(topnode);
  
  return item;
}


/* returns the item on top of the stack; returns NULL if error */
void* top(STACK s)
{
  if (isEmpty(s))
    return NULL;
  return s->top->pdata;
}

