so after trying many different models, I found a solution though again, rather length. any improvements over it?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int data_t;
typedef struct node node_t;
struct node
{
data_t data;
node_t *next;
} ;
typedef struct
{
node_t *head;
node_t *foot;
} list_t;
list_t
*make_empty_list(void) {
list_t *list;
list = malloc(sizeof(list_t));
assert(list!=NULL);
list->head = list->foot = NULL;
return list;
}
list_t
*insert_in_order (list_t *list, data_t value)
{
node_t *new, *curr, *prev;
new = malloc (sizeof (node_t));
new->next = NULL;
new->data = value;
if (list->head == NULL) /*First in*/
{
list->foot = list->head = new;
return list;
}
else
{
if (value <= list->head->data) /*Smaller than the head, so insert there*/
{
new->next = list->head;
list->head = new;
return list;
}
else
{
if (value > list->foot->data)/*Larger than the foot so insert there*/
{
list->foot->next = new;
list->foot = new;
return list;
}
else
{ /*we are somewhere between H & F, find the right place*/
prev = list->head;
curr = list->head->next;
while (curr->data < value)
{/*Move through list, stop when the curr node data is larger than value*/
prev = curr;
curr = curr->next;
}
/*Now at the right spot in the body of the list, insert*/
new->next = curr;
prev->next = new;
return list;
}
}
}
}
list_t
*read_into_list (void)
{
list_t *list;
int value;
list = make_empty_list ();
while ((scanf("%d", &value)) != EOF)
{
list = insert_in_order (list, value);
}
return list;
}
void
print_list(list_t *list)
{
node_t *ptr;
ptr = list->head;
while (ptr != NULL)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
}
void
free_list(list_t *list)
{
node_t *curr, *prev;
assert(list!=NULL);
curr = list->head;
while (curr) {
prev = curr;
curr = curr->next;
free(prev);
}
free(list);
}
int
main (int argc, char **argv)
{
list_t *list;
list = read_into_list ();
print_list (list);
free_list (list);
return 0;
}