/* This program uses code from "Algorithms in C, Third Edition,"
 *               by Robert Sedgewick, Addison-Wesley, 1998.
 */

#include <stdio.h>
#include <stdlib.h>

#include "lists.h"
#include "stacks.h"


struct stack_struct
{
   list items;
};

Stack newStack()
{
   Stack result = malloc(sizeof(*result));
   result->items = newList();
   return result;
}

// Argument max_size is ignored. This function is provided simply
// so that the list-based implementation offers the same public interface
// as the array-based implementation.
Stack newStack1(int max_size)
{
   Stack result = malloc(sizeof(*result));
   result->items = newList();
   return result;
}


void destroyStack(Stack stack)
{
   destroyList(stack->items);
   free(stack);
}


void push(Stack stack, void * content)
{
   link new_link = newLink(content);
   insertAtBeginning(stack->items, new_link);
}


void * pop(Stack stack)
{
   if (stackEmpty(stack))
   {
      printf("error: stack is empty, cannot pop\n");
      exit(1);
   }

   link top = deleteAtBeginning(stack->items);
   void * item = linkItem(top);
   free(top);
   return item;
}


int stackEmpty(Stack stack)
{
   return listEmpty(stack->items);
}

void pushInt(Stack stack, int value)
{
   int * content = malloc(sizeof(int));
   *content = value;
   push(stack, content);
}

int popInt(Stack stack)
{
   int * top = (int *) pop(stack);
   int result = *top;
   free(top);
   return result;
}

void printIntStack(Stack stack)
{
   int counter = 0;
   link i;
   printf("\n");
   for (i = listFirst(stack->items); i != NULL; i = linkNext(i))
   {
      int * item = (int *) linkItem(i);
      printf("position %d from the top: %d\n", counter, *item);
      counter++;
   }
   printf("\n");
}
