I was at an interview for a C position in which they presented me with an idiom that I haven't previously encountered. This is a trick that simplifies implementation of various algorithms involving linked lists and I'm wondering if anybody else has encountered this.
Say we have a linked list record defined so:
typedef struct _record
{
char* value;
struct _record* next;
} record;
We need a function that inserts a new record so that the entire list remains sorted with respect to the value's in the records. The following implementation is simpler than anything I would have used, albeit less readable.
void insert_sorted(record** r, const char* value)
{
record* newrec = NULL;
while(*r && strcmp(value, (*r)->value) > 0)
r = &((*r)->next); /* move r to point to the next field of the record */
newrec = malloc(sizeof(record));
newrec->value = strdup(value);
newrec->next = *r;
*r = newrec;
}
When the function is called, r points to the head pointer of the list. During the while loop, r is updated to point to the next
field of the record that comes just before the point where we want to put the new record in. The last line of the function either updates the head pointer of the list (if the insertion happens at the beginning) or the next
field of the previous record, which is quite cool.
A couple of questions:
Does this idiom have a name or is it mentioned in any literature?
Are there others like it in the C language?
I thought I knew C pretty well and had pointers and indirection pretty well figured out, but this one took me a while to fully understand.