#include <stdio.h>
#include <xparameters.h>
#include <xuartlite_l.h>

struct list *add_list( struct list *head, int num ) ;
struct list *delete_list( struct list *head, int num );
void print_list( struct list *head ) ;
void free_list( struct list *head ) ;

struct list {
	int num ;
	struct list *next ;
} ;

int main()
{
	int i = 0 ;
	struct list *head = NULL ;
	int arr[10] = { 2, 4, 8, 1, 3, 6, 5, 0, 9, 7 } ;

	print("Adding to list....\r\n") ;
	for( i=0; i < 10; i++ ){
		head = add_list( head, arr[i] ) ;
	}
	print_list( head ) ;
	print("Deleting the list elements.. 0,5,9\r\n") ;
	head = delete_list( head, 0 ) ;
	head = delete_list( head, 5 ) ;
	head = delete_list( head, 9 ) ;
	print_list( head ) ;
	print("Adding to list....\r\n") ;
	head = add_list( head, arr[7] ) ;
	head = add_list( head, arr[6] ) ;
	head = add_list( head, arr[8] ) ;
	print_list( head ) ;
	free_list( head ) ;
	process_exit() ;
}

struct list *add_list( struct list *head, int num ) 
{
	struct list *temp, *prev, *next ;

	temp = (struct list *)bufmalloc( sizeof(struct list) ) ;
	if( temp == NULL ) {
		print("Null\r\n") ;
		process_exit() ;
	}
	temp->num = num ;
	if( (head == NULL) || (temp->num <= head->num) ) {
		temp->next = head ;
		return temp ;
	}
	next = head->next ;
	prev = head ;
	while( (next != NULL) && (next->num <= num) ) {
		prev = next ;
		next = next->next ;
	}
	prev->next = temp ;
	temp->next = next ;
	return head ;
}

struct list *delete_list( struct list *head, int num )
{
	struct list *prev, *next ;

	if( head == NULL ) return NULL ;
	if( head->num == num ) {
		next = head ;
		head = head->next ;
		buffree(next) ;
		return head ;
	}
	prev = head ;
	next = head->next ;
	while( (next != NULL) && (next->num != num) ) {
		prev = next ;
		next = next->next ;
	}
	if( next != NULL ) {
		prev->next = next->next ;
		buffree(next) ;
	}
	return head ;
}

void free_list( struct list *head ) 
{
	struct list *prev ;

	while( head != NULL ) {
		prev = head ;
		head = head->next ;
		buffree( prev ) ;
	}
}

void print_list( struct list *head ) 
{
	struct list *temp = head ;
	while( temp != NULL ) {
    		XUartLite_SendByte(XPAR_MYUART_BASEADDR, '0'+temp->num) ;
		//printf("Num : %d\n", temp->num ) ;
		temp = temp->next ;
	}
	print("\r\n\n") ;
}
