/* Standard C */
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

/* Project */
#include "util.h"

typedef int T;

struct stack_item {
	struct stack_item *next;
	T data;
};

struct stack {
	struct stack_item *head;
};

void
stack_init(struct stack *stack)
{
	stack->head = NULL;
}

void
stack_push(struct stack *stack, T data)
{
	struct stack_item *new_item;

	if ( (new_item = malloc(sizeof(*new_item))) != NULL ) {
		new_item->data = data;
		new_item->next = stack->head;
		stack->head = new_item;
	}
	else
		ERROR("out of memory");
}

bool
stack_pop(struct stack *stack, T *data)
{
	if ( stack->head != NULL ) {
		struct stack_item *next = stack->head->next;
		*data = stack->head->data;
		free(stack->head);
		stack->head = next;

		return true;
	}
	else
		return false;
}

bool
stack_empty(struct stack *stack)
{
	return stack->head == NULL;
}

void
stack_free(struct stack *stack)
{
	struct stack_item *item, *next;

	for ( item = stack->head; item; item = next ) {
		next = item->next;
		free(item);
	}
}

int
main()
{
	struct stack stack[1];

	stack_init(stack);

	for ( int i = 0; i != 10; ++i )
		stack_push(stack, i);

	/*
	while ( !stack_empty(stack) ) {
		int i;
		if ( stack_pop(stack, &i) )
			printf("%d\n", i);
		else
			ERROR("this shouldn't happen!");
	}
	*/

	stack_free(stack);

	return EXIT_SUCCESS;
}



