#include <stdio.h>
#include <string.h>
#include <stdlib.h>

//struct ListData {
//	int		data;
//};

typedef struct listItem listItem;

struct listItem {
	listItem* next;
	int value;
	//struct ListData* data;
};

typedef struct {
	listItem* head;
	listItem* tail;
} list;

listItem* listNewItemLinked(int value, listItem* next) {
	listItem* newItem = (listItem*)malloc(sizeof(listItem));
	newItem->value = value; newItem->next = next;
	return newItem;
}

listItem* listNewItem(int value) {
	return listNewItemLinked(value, NULL);
}

void listDelete(list* list) {
	listItem* current = list->head;
	while(current) {
		listItem* tmp = current->next;
		free(current);
		current = tmp;
	}
	list->head = NULL;
	list->tail = NULL;
}

void listPush(list* list, listItem* item) {
	listItem* last = item;
	while(last->next) last=last->next;
	last->next = list->head;
	list->head = item;
	if (!list->tail)
		list->tail = last;
}

void listPushBack(list* list, listItem* item) {
	listItem* last = item;
	while(last->next) last=last->next;
	if (list->tail)
		list->tail->next = item;
	list->tail = last;

	if(!list->head)
		list->head = item;
}

void listForEach(list* list, void (*func)(listItem* item)) {
	listItem* current = list->head;
	while(current) {
		func(current);
		current = current->next;
	}
}

void printItem(listItem* item) {
	printf("%d\n", item->value);
}

int main() {
	list l =  {NULL, NULL};

	//Example 1 push linked list items => 1 -> 2 -> 3 -> ...
	//listPush(&l, listNewItemLinked(1, listNewItemLinked(2, listNewItemLinked(3, NULL))));

	//Example 2 push back => ... -> 1 -> 2 -> 3
	listPushBack(&l , listNewItem(1));
	listPushBack(&l , listNewItem(2));
	listPushBack(&l , listNewItem(3));

	//Example 3 push front => 3 -> 2 -> 1 -> ...
	//listPush(&l, listNewItem(1));
	//listPush(&l, listNewItem(2));
	//listPush(&l, listNewItem(3));

	//Example 4 push back linked list items => ... -> 4 -> 5 -> 6
	//listPushBack(&l, listNewItemLinked(4, listNewItemLinked(5, listNewItemLinked(6, NULL))));

	listForEach(&l, printItem);

	listDelete(&l);
}