lundi 30 mars 2015

Inserting an element in a list without tail or head



I've got a little problem about an exercice which is supposed to explain how malloc works.


For starters, here's the header we have been given:



struct cell_m
{
unsigned int magicnumber ;
struct cell_m *next ;
void *userspacestart ;
void *userspacestop ;
};

typedef struct cell_m *liste_t ;


As you can see, i have only a next pointer so it's a simple chained list. I am supposed to code a function to insert a cell_m inside a liste_t of cell_m. There is one condition, the size of the cell_m that we want to insert must be smaller than the one we're currently at. Here's my code of this function :



void insert(liste_t *list, liste_t cell)
{
liste_t *old_list = malloc(sizeof(liste_t*));

if (sizeof((*list)->userspacestop) - (sizeof((*list)->userspacestart))
>= (sizeof(cell->userspacestop)) - (sizeof(cell->userspacestart)))
/*insert at the begining*/
else
{
old_list = list;
(*list) = (*list)->next;
while ((*list)->next != NULL)
{
if (sizeof((*list)->userspacestop) - (sizeof((*list)->userspacestart))
>= (sizeof(cell->userspacestop)) - (sizeof(cell->userspacestart)))
{
(*old_list)->next = cell;
cell->next = (*list);
break;
}
old_list = list;
(*list) = (*list)->next;
}
}
}


A little explanation : I try to keep the last position of where i was in the list so i created an "old_list" variable to keep it. At first, i try to see if i can directly insert my cell at the beginning of the list. I'm not entirely sure what to put here so i put a comment for now. Then, if it's not possible to insert it at the begining, i move forward into my list and try to insert the element. (then again, not entirely sure if the code for inserting is right)


Is this any good or am i totally wrong with this code? Thank you !




Aucun commentaire:

Enregistrer un commentaire