Download Modular C
Transcript
Chapter 8: Example: Ordered Set
struct oset
{
lessfun less;
list elements;
};
oset
oset_create(lessfun less)
{
oset tmp = (oset) malloc(sizeof(struct oset));
tmp -> less = less;
tmp -> elements = 0;
return tmp;
}
typedef list *position;
/* return the first position p greater than or equal to the one given such
that either p is the last position (no element has that position) or
the element given as argument is smaller than or equal to the one at p */
static position
posit(position initial_pos, void *element, lessfun less)
{
position p = initial_pos;
for(; *p && less((*p) -> element, element); p = &((*p) -> next))
;
return p;
}
/* insert an element at the position given if and only if the element at
that position is not equal to the one we want to insert */
static void
insert_if_nonequal(position p, void *element, lessfun less)
{
if(less(element, (*p) -> element))
{
/* then the elements are not the same, insert the new one */
list l = (list) malloc(sizeof(struct list));
l -> next = *p;
l -> element = element;
*p = l;
}
}
void
oset_insert(oset s, void *element)
{
position p = posit(&(s -> elements), element, s -> less);
insert_if_nonequal(p, element, s -> less);
}
int
oset_member(oset s, void *element)
{
list *lp = posit(&(s -> elements), element, s -> less);
30