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.
I’ve used similar to this to insert into a binary tree. Because when iterating the tree, you usually stop when your pointer becomes
NULL(you ran off the tree).So to insert, you have 3 options,
1: use a variable which tracks the previous value of your iterating pointer.
2: stop when the pointer you would follow is NULL before you follow it, works but slightly less elegant in my opinion.
3: or a more elegant solution is simply use a pointer to a pointer, so you can just do:
*it = new_node();and it’ll add it where theNULLused to be in your tree.For a linked list, while this code works nicely, I usually just use a doubly linked list which makes it trivial to insert at any location.