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

struct student{
	int id;
	char name[20];
};

struct nodeR{
	struct student s;
	struct nodeR* next;
};

typedef struct nodeR* node;

struct listR{
	node head;
};

typedef struct listR* list;


list createList();
void printNode(node );
void printList(list );
node createNode(int , char *);
void addNodeAtStart(list , node );
void addNodeAtEnd(list , node );
node findNodeById(list , int );
int deleteNode(list , node );
void destroyList(list );


list createList(){
	list l = malloc(sizeof(struct listR));
	if (l == NULL){
		abort();
	}
	l->head = NULL;
	return l;
}

void printNode(node n){
	printf("Student's data:\n");
	printf("id: %d\tname: %s\n",n->s.id,n->s.name);
}

void printList(list l){
	node currentNode = l->head;
	while(currentNode != NULL){
		printNode(currentNode);
		currentNode = currentNode->next;
	}
}

node createNode(int id, char *name){
	node n = malloc(sizeof(struct nodeR));
	if (n == NULL){
		abort();
	}
	n->s.id = id;
	strcpy(n->s.name,name);
	n->next = NULL;

	return n;
}

void addNodeAtStart(list l, node n){
	n->next = l->head;
	l->head = n;
}

void addNodeAtEnd(list l, node n){
	n->next = NULL;

	if (l->head == NULL){
		l->head = n;
		return;
	}

	node currentNode = l->head;
	while(currentNode->next != NULL){
		currentNode = currentNode->next;
	}
	currentNode->next = n;
}

node findNodeById(list l, int id){
	node currentNode = l->head;
	while(currentNode != NULL){
		if (currentNode->s.id == id){
			return currentNode;
		}
		currentNode = currentNode->next;
	}
	return NULL;
}

int deleteNode(list l, node n){
	node currentNode = l->head;
	node previousNode = l->head;

	while(currentNode != NULL){
		if (currentNode == n){
			previousNode->next = currentNode->next;
			free(currentNode);
			return 1;
		}
		previousNode = currentNode;
		currentNode = currentNode->next;
	}
	return -1;
}

void destroyList(list l){
	node currentNode = l->head;
	while(currentNode != NULL){
		node tmp = currentNode->next;
		free(currentNode);
		currentNode = tmp;
	}
	free(l);
}

int main(int argc, char **argv){
	list l = createList();
	for(int i=0;i<100;i++){
		node n = createNode(i,"John");
		addNodeAtEnd(l,n);
	}
	node n = findNodeById(l,15);
	deleteNode(l,n);
	printList(l);
	destroyList(l);
}










