Hacker News new | ask | show | jobs
by hadcomplained 2024 days ago
The following is the code I wrote before reading the example pieces of code.

    void remove(IntList* l, IntListItem* target) {
      if (l->head == target) {
        l->head = l->head->next;
        return;
      }
      IntListItem* prev = l->head;
      while (prev->next != target) prev = prev->next;
      prev->next = prev->next->next;
    }
Skimming the comments here, I was surprised not to see an equivalent piece of code mentioned. To me my code is more readable than both of the first and second examples presented in the article. Does that mean my taste is peculiar?
3 comments

I kinda like this version best. It makes clear we're updating a ->head pointer in one case and ->next in the others. I like the elegant version, too, since it can update both kinds of pointers in one fell swoop, but you have to grok that p starts as a head pointer and later becomes something's next pointer.

I'd say C syntax for double pointers is a lot less kind than the syntax for single pointers. Your version thankfully lacks any line like so, without making me think about parens

    p = &(*p)->next;
This is exactly the right answer.

There are two cases here (1. when the target is at the front of the list and necessitates changing the head of list, and 2. when the head doesn't need to be changed.) You handle both the cases separately.

Both the classical and the "elegant" versions are worse than this one.

Linus' point is that this way of thinking produces this "edge case".

There is no "head case", all members of the list are the same. The head isn't a special element.

Your version does a lot more memory writes.